# AES-128-CBC 加密和解密
此文档提供了一个使用 CryptoJS 库在 JavaScript 中实现 AES-128-CBC 加密和解密 UTF-8 编码数据的示例。
# 使用说明
1、安装 CryptoJS 库:
npm install crypto-js |
创建一个名为 aes-utils.js 的新文件
// aes-utils.js | |
import CryptoJS from 'crypto-js'; | |
/** | |
* AES-128-CBC 加密 | |
* @param {string} plaintext 待加密的明文数据 | |
* @param {string} key 密钥字符串 (必须是 16 个字符) | |
* @param {string} iv 初始化向量 (必须是 16 个字符) | |
* @returns {string} 加密后的密文 | |
*/ | |
export function encrypt(plaintext, key, iv) { | |
const keyBytes = CryptoJS.enc.Utf8.parse(key); | |
const ivBytes = CryptoJS.enc.Utf8.parse(iv); | |
const ciphertext = CryptoJS.AES.encrypt(plaintext, keyBytes, { | |
iv: ivBytes, | |
mode: CryptoJS.mode.CBC, | |
padding: CryptoJS.pad.Pkcs7 | |
}).toString(); | |
return ciphertext; | |
} | |
/** | |
* AES-128-CBC 解密 | |
* @param {string} ciphertext 待解密的密文数据 | |
* @param {string} key 密钥字符串 (必须是 16 个字符) | |
* @param {string} iv 初始化向量 (必须是 16 个字符) | |
* @returns {string} 解密后的明文 | |
*/ | |
export function decrypt(ciphertext, key, iv) { | |
const keyBytes = CryptoJS.enc.Utf8.parse(key); | |
const ivBytes = CryptoJS.enc.Utf8.parse(iv); | |
const bytes = CryptoJS.AES.decrypt(ciphertext, keyBytes, { | |
iv: ivBytes, | |
mode: CryptoJS.mode.CBC, | |
padding: CryptoJS.pad.Pkcs7 | |
}); | |
const plaintext = bytes.toString(CryptoJS.enc.Utf8); | |
return plaintext; | |
} |
在你的主 JavaScript 文件中,导入 aes-utils.js 文件中的 encrypt 和 decrypt 函数:
import { encrypt, decrypt } from './aes-utils'; |
const plaintext = '你好, 世界!'; | |
const key = '0123456789abcdef'; | |
const iv = 'fedcba9876543210'; | |
const ciphertext = encrypt(plaintext, key, iv); | |
console.log('密文:', ciphertext); | |
const decryptedText = decrypt(ciphertext, key, iv); | |
console.log('解密后的明文:', decryptedText); |
# 说明
1、encrypt 函数接受三个参数:
- plaintext: 待加密的明文数据 (UTF-8 编码)
- key: 16 个字符的加密密钥
- iv: 16 个字符的初始化向量 (IV)
该函数使用 AES-128-CBC 算法对明文进行加密,并返回密文。
2、decrypt 函数接受三个参数:
- ciphertext: 待解密的密文数据
- key: 与加密时使用的相同的 16 个字符密钥
- iv: 与加密时使用的相同的 16 个字符初始化向量 (IV)
3、该函数使用 AES-128-CBC 算法对密文进行解密,并返回明文。
密钥和初始化向量必须都是 16 个字符长 (128 位) 的字符串,用于 AES-128-CBC 算法。
4、你可以使用任意 16 个字符的随机字符串作为密钥和初始化向量。CryptoJS 库会自动处理输入字符串到字节数组的转换,用于加密和解密操作。