最近有个项目,因为参数里面带有sql可能是客户网关对参数做了防侵入,用简单的base64加密后居然还是不行,决定用AES加密。代码如下。
/**
* 参数加密私钥
*/
static final String paramPrivateKey="3dae12897b044f96";
/**
* 加密
* @param sSrc
* @return
* @throws Exception
*/
public static String paramEncrypt(String sSrc) throws Exception {
if (paramPrivateKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (paramPrivateKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = paramPrivateKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
/**
* 解密
* @param sSrc
* @return
* @throws Exception
*/
public static String paramDecrypt(String sSrc){
try {
if(!StringUtils.hasLength(sSrc)){
return "";
}
// 判断Key是否正确
if (paramPrivateKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (paramPrivateKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = paramPrivateKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original,"utf-8");
return originalString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
这部分代码,网上很多,重点是同样的字符串加密后与在线网站的结果不一致,AES 加密/解密 - 在线工具 (toolhelper.cn)。打开网站看到有很多选项,经过查询才知道,java生成的都是使用默认参数,参考地址:JAVA实现AES加密、解密 - 奕锋博客 - 博客园 (cnblogs.com)。