转载请注明版权
跟同事试了很久,才找到能在浏览器/小程序上用CryptoJS进行AES-ECB-128加密,在后端对应地用Java解密的办法(支持中文,无需escape()),分享给大家。感谢英明。
最新版CryptoJS地址:https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js
注:不推荐aes-js、斯坦福的Sjcl这两个库,第一个对明文长度有要求,第二个几乎没有文档。
JS部分:
/**
* 明文用AES加密并以Base64格式导出
*/
function aesEncrypt(plainText, key){
var text = CryptoJS.enc.Utf8.parse(plainText);
var utf8Key = CryptoJS.enc.Utf8.parse(key); //此处必须Parse!!!!!
//用AES/ECB/Pkcs7加密
var encrypt = CryptoJS.AES.encrypt(text, utf8Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
//把结果转成Base64并发送给后端
return CryptoJS.enc.Base64.stringify(encrypt.ciphertext);
}
Java部分:
/**
* cipherTextBase64为Base64格式密文
*/
public static byte[] aesDecrypt(String cipherTextBase64, String key) {
if (cipherTextBase64 == null || cipherTextBase64.length() == 0) {
return null;
}
byte[] cipherTextBytes = Base64.getDecoder().decode(cipherTextBase64); //解Base64
byte[] decryptedByteArray = null;
try {
// 创建AES秘钥
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 初始化解密器
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// 解密
decryptedByteArray = cipher.doFinal(cipherTextBytes);
} catch (Exception e) {
e.printStackTrace();
}
return new String(decryptedByteArray, "UTF-8");
}
网友评论