|
楼主 |
发表于 2022-8-31 13:37:44
|
显示全部楼层
江苏省宿迁市
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
*
* @author shen_feng 加密解密
*/
public class AesUtil {
// static String sKey = "HOPERUN.COM";
/**
* 密钥如超过16位,截至16位,不足16位,补/000至16位
*
* @param key原密钥
* @Return 新密钥
*/
public static String secureBytes(String key) {
if (key.length() > 16) {
key = key.substring(0, 16);
} else if (key.length() < 16) {
for (int i = (key.length() - 1); i < 15; i++) {
key += "\000";
}
}
return key;
}
/**
* AES解密 用于数据库储存
*
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String decryptCode(String sSrc, String key) {
String sKey = secureBytes(key);
try {
// 判断Key是否正确
if (sKey == null) {
// LogUtil.d("AesUtil", "Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
// LogUtil.d("AesUtil", "Key长度不是16位");
sKey = secureBytes(sKey);
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "GBK");
return originalString;
} catch (Exception e) {
return null;
}
} catch (Exception ex) {
return null;
}
} |
|