1、下载地址:crypto-js库下载地址
2、按模块引入项目:
<!-- aes解密 -->
<script type="text/javascript" src="../components/cryptojs-3.1.2/rollups/aes.js"></script>
3、加解密方法封装:
// aesEncrypt aes加密
function aesEncrypt(data){
var key = CryptoJS.enc.Utf8.parse('0123456789abcdef');
var encrypted = CryptoJS.AES.encrypt(data, key, {
iv: key,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
// 转换为字符串
encrypted = encrypted.toString();
return encrypted;
}
// aesDecrypt aes解密
function aesDecrypt(encrypted){
var key = CryptoJS.enc.Utf8.parse('0123456789abcdef');
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: key,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
// 转换为 utf8 字符串
decrypted = CryptoJS.enc.Utf8.stringify(decrypted);
return decrypted;
}
4、应用:
// 加密
var 密文 = aesEncrypt(明文字符串);
// 解密
var 明文 = aesDecrypt(密文 );