vue里使用crypto-js实现AES加解密
Posted 凯小默
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue里使用crypto-js实现AES加解密相关的知识,希望对你有一定的参考价值。
安装
npm install crypto-js
加密
import CryptoJS from "crypto-js";
// AES加密
function encryptByAES(word, keyStr)
keyStr = keyStr ? keyStr : "kaimo313";
let key = CryptoJS.enc.Utf8.parse(keyStr);
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
);
return encrypted.toString();
解密
import CryptoJS from "crypto-js";
// AES解密
function decryptByAES(word, keyStr)
keyStr = keyStr ? keyStr : "kaimo313";
let key = CryptoJS.enc.Utf8.parse(keyStr);
let decrypt = CryptoJS.AES.decrypt(word, key,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
);
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AES加密解密</title>
<script src="./crypto-js.js"></script>
</head>
<body>
<script>
console.log("CryptoJS---->", CryptoJS)
// AES加密
function encryptByAES(word, keyStr)
keyStr = keyStr ? keyStr : "kaimo313";
let key = CryptoJS.enc.Utf8.parse(keyStr);
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
);
return encrypted.toString();
// AES解密
function decryptByAES(word, keyStr)
keyStr = keyStr ? keyStr : "kaimo313";
let key = CryptoJS.enc.Utf8.parse(keyStr);
let decrypt = CryptoJS.AES.decrypt(word, key,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
);
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
console.log("使用 key:kaimo313 对密码 123456 进行加密", encryptByAES("123456"));
console.log("使用 key:kaimo313 对密码 123456 进行解密", decryptByAES(encryptByAES("123456")));
</script>
</body>
</html>
以上是关于vue里使用crypto-js实现AES加解密的主要内容,如果未能解决你的问题,请参考以下文章