推荐答案
// www.javascriptcn.com code example
const crypto = require('crypto');
// AES加密
function encryptAES(text, key, iv) {
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// AES解密
function decryptAES(encryptedText, key, iv) {
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// 示例
const key = crypto.randomBytes(32); // 256位密钥
const iv = crypto.randomBytes(16); // 初始化向量
const text = 'Hello, AES!';
const encrypted = encryptAES(text, key, iv);
console.log('Encrypted:', encrypted);
const decrypted = decryptAES(encrypted, key, iv);
console.log('Decrypted:', decrypted);本题详细解读
AES加密算法简介
AES(Advanced Encryption Standard)是一种对称加密算法,广泛用于数据加密和解密。它支持128位、192位和256位的密钥长度。AES加密过程包括多轮的数据替换、置换和混淆操作,确保数据的安全性。
加密过程
- 初始化向量(IV):IV是一个随机生成的16字节数据,用于增加加密的随机性,防止相同的明文生成相同的密文。
- 密钥:AES-256使用32字节的密钥。
- 加密:使用
crypto.createCipheriv方法创建加密器,指定算法为aes-256-cbc,并传入密钥和IV。然后使用cipher.update和cipher.final方法进行加密。
解密过程
- 解密:使用
crypto.createDecipheriv方法创建解密器,同样指定算法为aes-256-cbc,并传入密钥和IV。然后使用decipher.update和decipher.final方法进行解密。
注意事项
- 密钥管理:密钥的安全性至关重要,必须妥善保管,避免泄露。
- IV的随机性:每次加密时都应使用不同的IV,以增强安全性。
- 填充模式:AES加密通常使用PKCS7填充模式,确保数据块大小符合要求。
通过上述代码示例,可以轻松实现AES加密和解密操作,适用于微信小程序中的数据安全保护。