一、CDN插件
地址:https://cdnjs.com/libraries/crypto-js
可以直接引用线上CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js" integrity="sha512-E8QSvWZ0eCLGk4km3hxSsNmGWbLtSCSUcewDQPQWZF6pEU8GlT8a5fF32wOl1i8ftdMhssTrF/OhyGWwonTcXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
或者保存到本地文件
二、具体实现
1. 字段解释
key:密钥,16/24/32位
iv:偏移量 ,16位,可与key一致
message:需要加密的文本信息
plaintext:明文
ciphertext:密文
2. 只需要密钥的加密与解密
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>基于JavaScript的AES加密与解密实现</title>
</head>
<body>
<script src="js/crypto-js.min.js"></script>
<script type="text/javascript">
var key = "0123456789abcdef"; // 密钥
var message = '1234567890abcdefghigklmnopqrstuvwxyz!@#$%^&*(){}:"<>?|'; // 需要加密的信息
// 加密实现
function encrypt(plaintext) {
var encrypted = CryptoJS.AES.encrypt(plaintext, key);
var ciphertext = encrypted.toString();
return ciphertext;
}
// 解密实现
function decrypt(ciphertext) {
var plaintext = CryptoJS.AES.decrypt(ciphertext, key).toString(CryptoJS.enc.Utf8);
return plaintext;
}
var ciphertext = encrypt(message);
var plaintext = decrypt(ciphertext);
console.log("密文:", ciphertext); // 密文:U2FsdGVkX18GahFCkjnFSAJ0QJuM4dh5sB35cQAsVApQ1zf6AcM2w2jnlenIoaax5VCV390+i1+ZWvrsulYhvPeI+YWl294/SY6D5Os0zvA=
console.log("明文:", plaintext); // 明文:1234567890abcdefghigklmnopqrstuvwxyz!@#$%^&*(){}:"<>?|
</script>
</body>
</html>
3.需要密钥和偏移量的加密与解密
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>基于JavaScript的AES加密与解密实现</title>
</head>
<body>
<script src="js/crypto-js.min.js"></script>
<script>
var key = CryptoJS.enc.Utf8.parse("0123456789abcdef"); // 密钥
var iv = CryptoJS.enc.Utf8.parse("0123456789abcdef"); // 偏移量
var message = '1234567890abcdefghigklmnopqrstuvwxyz!@#$%^&*(){}:"<>?|'; // 需要加密的信息
// 加密实现
function encrypt(plaintext) {
var encrypted = CryptoJS.AES.encrypt(plaintext, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var ciphertext = encrypted.toString();
return ciphertext;
}
// 解密实现
function decrypt(ciphertext) {
var decrypted = CryptoJS.AES.decrypt(ciphertext, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);
return plaintext;
}
var ciphertext = encrypt(message);
var plaintext = decrypt(ciphertext);
console.log("密文:", ciphertext); // 密文:dbPloHkdKgBH2huMBKZlMkbHSdp4fgoTouVu6ZAHMV1A9Vg+n7VkzwryY6ASpsHuA1sHWQwvJr0mala0L2WAVA==
console.log("明文:", plaintext); // 明文:1234567890abcdefghigklmnopqrstuvwxyz!@#$%^&*(){}:"<>?|
</script>
</body>
</html>
4.验证
在线验证网址:https://www.ssleye.com/ssltool/aes_cipher.html
文章版权声明
1 原创文章作者:1230,如若转载,请注明出处: https://www.52hwl.com/38230.html
2 温馨提示:软件侵权请联系469472785#qq.com(三天内删除相关链接)资源失效请留言反馈
3 下载提示:如遇蓝奏云无法访问,请修改lanzous(把s修改成x)
4 免责声明:本站为个人博客,所有软件信息均来自网络 修改版软件,加群广告提示为修改者自留,非本站信息,注意鉴别