private static String byteArrayToHexString(byte[] raw) {
StringBuilder sb = new StringBuilder(2 + raw.length * 2);
// sb.append("0x");
for (int i = 0; i < raw.length; i++) {
sb.append(String.format("%02X", Integer.valueOf(raw[i] & 0xFF)));
}
return sb.toString();
}
private static byte[] hexStringToByteArray(String hex) {
Pattern replace = Pattern.compile("^0x");
String s = replace.matcher(hex).replaceAll("");
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++){
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte)v;
}
return b;
}
/*
* 解密
*/
private static String Decrypt(String sSrc, String sKey) throws Exception {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
byte[] enCodeFormat = shortmd5(sKey);
SecretKeySpec skeySpec = new SecretKeySpec(enCodeFormat , "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE , skeySpec);
byte[] encrypted1 = hexStringToByteArray(sSrc);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
}
/*
* 加密
*/
private static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
byte[] enCodeFormat = shortmd5(sKey);
SecretKeySpec skeySpec = new SecretKeySpec(enCodeFormat , "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE , skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return byteArrayToHexString(encrypted).toLowerCase();
}
private static byte[] shortmd5(String b) throws Exception
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(b.getBytes("UTF-8"));
byte[] digest = md.digest();
return digest;
}
/*
* 加密
*/
public static String KeyEncrypt(String UnitID,String DeptID,String DeptName,String UserID, String UserName) throws Exception {
String _key ="and@123_."+UnitID;
String _DeptID = AES.Encrypt(DeptID,_key+"deptid");
String _DeptName = AES.Encrypt(DeptName,_key+"deptname");
String _UserID = AES.Encrypt(UserID,_key+"userid");
String _UserName = AES.Encrypt(UserName,_key+"username");
String _keyid =_DeptID+"_"+_DeptName+"_"+_UserID+"_"+_UserName;
return _keyid;
}
/*
* 加密
*/
public static String KeyEncrypt(String UnitID,String UserID) throws Exception {
String _key ="and@123_."+UnitID;
String _UserID = AES.Encrypt(UserID,_key+"userid");
return _UserID;
}
/**
* 解密为Userid
* @param UnitID
* @param content
* @return
*/
public static String DeCodeUserId(String UnitID,String content){
String _key ="and@123_."+UnitID;
String key = content.split("_")[2];
try {
return AES.Decrypt(key, _key+"userid");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}原文:http://blog.csdn.net/de_ruiyu/article/details/42024357