package tianya.cn.main;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.log4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/** 第一种
* 用户密码加密解密
*/
public class Crypt {
public static Logger logger = Logger.getLogger(Crypt.class.getName());
public static String KEYSTRING="202cb962ac59075b964b07152d234b70";
// --------------------------------------------------------------------------------------------
// 获得密钥
public static SecretKey getKey(String s) throws Exception {
// s ="g8TlgLEc6oqZxdwGe6pDiKB8Y";
// System.out.println("s==" + s);
char[] ss = s.toCharArray();
String sss = "";
for (int i = 0; i < ss.length; i = i + 2) {
sss = sss + ss[i];
}
SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
DESKeySpec ks = new DESKeySpec(sss.substring(0, 8).getBytes());
SecretKey kd = kf.generateSecret(ks);
return kd;
}
// --------------------------------------------------------------------------------------------------
// 返回加密后的字符串
// key是用于生成密钥的字符串,input是要加密的字符串
public static String getEncryptedString(String key, String input) {
String base64 = "";
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, getKey(key));
// System.out.print("getKey(key)===" + getKey(key) + "key==" + key);
byte[] inputBytes = input.getBytes();
byte[] outputBytes = cipher.doFinal(inputBytes);
BASE64Encoder encoder = new BASE64Encoder();
base64 = encoder.encode(outputBytes);
} catch (Exception e) {
base64 = e.getMessage();
logger.debug("加密出错:"+e.getMessage());
}
return base64;
}
// --------------------------------------------------------------------------------------------------
// 返回解密后的字符串
// key是用于生成密钥的字符串,input是要解密的字符串
public static String getDecryptedString(String key, String input) {
String result = null;
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, getKey(key));
BASE64Decoder decoder = new BASE64Decoder();
byte[] raw = decoder.decodeBuffer(input);
byte[] stringBytes = cipher.doFinal(raw);
result = new String(stringBytes, "UTF8");
} catch (Exception e) {
result = e.getMessage();
logger.debug("解密出错:"+e.getMessage());
}
return result;
}
public static String getKeyByResource(){
// String str = ApplicationResource.getValueByKey("password.key"); //从配置文件中获取202cb962ac59075b964b07152d234b70
String str = "";
if(str!=null && !str.equals("")){
return str;
}else{
return KEYSTRING;
}
}
/**
* 加密
* @param input 加密前的字符串
* @return
*/
public static String getEncryptedString(String input){
return getEncryptedString( getKeyByResource(), input );
}
/**
* 解密
* @param input 加密后的字符串
* @return
*/
public static String getDecryptedString(String input) {
return getDecryptedString( getKeyByResource(), input );
}
}
/*==================================第二种===================================*/
package tianya.cn.main;
import java.security.MessageDigest;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* 字符串 DESede(3DES) 加密
*
* @param args在java中调用sun公司提供的3DES加密解密算法时
* ,需要使 用到$JAVA_HOME/jre/lib/目录下如下的4个jar包: jce.jar
* security/US_export_policy.jar security/local_policy.jar
* ext/sunjce_provider.jar
*/
public class Te {
private static final String Algorithm = "DESede"; // 定义加密算法,可用
// DES,DESede,Blowfish
public static void main(String[] args) {
// TODO Auto-generated method stub
// 添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final byte[] keyBytes = { 0x11, 0x22, 0x4F, 0x58,
(byte) 0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51,
(byte) 0xCB,
(byte) 0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte) 0x98, 0x30, 0x40, 0x36,
(byte) 0xE2
}; // 24字节的密钥
String szSrc = "This is a 3DES test. 测试";
System.out.println("加密前的字符串:" + szSrc);
byte[] encoded = encryptMode(keyBytes, szSrc.getBytes());
System.out.println("加密后的字符串:" + new String(encoded));
byte[] srcBytes = decryptMode(keyBytes, encoded);
System.out.println("解密后的字符串:" + (new String(srcBytes)));
}
// keybyte为加密密钥,长度为24字节
// src为被加密的数据缓冲区(源)
public static byte[] encryptMode(byte[] keybyte, byte[] src) {
try {
// 生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
// 加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);// 在单一方面的加密或解密
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
// keybyte为加密密钥,长度为24字节
// src为加密后的缓冲区
public static byte[] decryptMode(byte[] keybyte, byte[] src) {
try {
// 生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
// 解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
// 转换成十六进制字符串
public static String byte2Hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
if (n < b.length - 1)
hs = hs + ":";
}
return hs.toUpperCase();
}
/***
* 16位MD加密算法
*
* @param content
* @return 16位MD5
*/
private static String get16BitMd5(String content) {
String result = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] source = content.getBytes("utf-8");
char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
'd', 'e', 'f' };
md5.update(source);
byte tmp[] = md5.digest(); // MD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
// 换后的结果转换为字符串
result = new String(str);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/***
* 32位MD加密算法
*
* @param content
* @return 32位MD5
*/
private static String get32BitMd5(String content) {
// 返回字符串
String md5Str = null;
try {
// 操作字符串
StringBuffer buf = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
// 添加要进行计算摘要的信息,使用 content 的 byte 数组更新摘要。
md.update(content.getBytes());
// 计算出摘要,完成哈希计算。
byte b[] = md.digest();
int i;
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
// 将整型 十进制 i 转换为16位,用十六进制参数表示的无符号整数值的字符串表示形式。
buf.append(Integer.toHexString(i));
}
// 32位的加密
md5Str = buf.toString();
// 16位的加密
// md5Str = buf.toString().md5Strstring(8,24);
} catch (Exception e) {
e.printStackTrace();
}
return md5Str;
}
}