JavaScript中实现AES加密解密
JavaScript中实现AES加密解密方式一、加解密时需要秘钥(key)和秘钥偏移量(iv)
1、下载AES加密解密插件 (aes_1.js)
下载地址:https://github.com/hellobajie/AES-of-JavaScript
2、将该js文件引用到项目中
3、实例
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>需要秘钥(key)及秘钥偏移量(iv)的aes加解密</title>
</head>
<body>
<script src="aes_1.js"></script>
<script>
var key = CryptoJS.enc.Utf8.parse("十六位十六进制数作为秘钥");
var iv = CryptoJS.enc.Utf8.parse('十六位十六进制数作为秘钥偏移量');
function Encrypt(word){
srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv,mode:CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});
return encrypted.ciphertext.toString().toUpperCase();
}
function Decrypt(word){
var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
var decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv,mode:CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});
var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
var mm = Encrypt('nihao')
console.log(mm);
var jm = Decrypt(mm);
console.log(jm)
</script>
</body>
</html>
方式二、加解密时仅需要秘钥
1、下载AES加密解密插件 (aes_2.js)
下载地址:https://github.com/hellobajie/AES-of-JavaScript
2、将该js文件引用到项目中
3、实例
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>加解密时仅需要秘钥</title>
</head>
<body>
<script src="aes_2.js"></script>
<script type="text/javascript">
var pwd="秘钥";
function Encrypt(word){
return CryptoJS.AES.encrypt(word,pwd).toString();
}
function Decrypt(word){
return CryptoJS.AES.decrypt(word,pwd).toString(CryptoJS.enc.Utf8);
}
var mm = Encrypt('nihao');
console.log(mm)
var jm = Decrypt(mm);
console.log(jm)
</script>
</body>
</html>