// 引入 crypto 模块,这是 Node.js 内置的用于加密解密的模块
const crypto = require('crypto');
// 定义加密函数
function encrypt(text, secretKey) {
// 创建 Cipheriv 实例,使用 AES-192 算法
const cipher = crypto.createCipheriv('aes-192-cbc', secretKey, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// 定义解密函数
function decrypt(encryptedText, secretKey) {
// 创建 Decipheriv 实例,使用 AES-192 算法
const decipher = crypto.createDecipheriv('aes-192-cbc', secretKey, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// 生成一个随机的 16 字节 IV (Initialization Vector)
const iv = crypto.randomBytes(16);
// 定义一个 24 字节的密钥 (AES-192 需要 24 字节的密钥)
const secretKey = crypto.randomBytes(24);
// 示例文本
const text = 'Hello, World!';
console.log('Original Text:', text);
// 加密示例
const encryptedText = encrypt(text, secretKey);
console.log('Encrypted Text:', encryptedText);
// 解密示例
const decryptedText = decrypt(encryptedText, secretKey);
console.log('Decrypted Text:', decryptedText);
crypto
模块,这是 Node.js 内置的用于加密和解密操作的模块。encrypt
函数使用 AES-192 算法进行加密。它接受明文和密钥作为参数,并返回加密后的密文。decrypt
函数用于解密密文,同样使用 AES-192 算法,并返回原始的明文。希望这段代码对你有所帮助!
上一篇:nodejs opencv
下一篇:js sm3加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站