JavaScript前端的AES加密与解密实现

网站建设1年前发布 Cam2023
74 00

一、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​

JavaScript前端的AES加密与解密实现

© 版权声明

相关文章