// 对称加密示例代码:使用AES算法
// 引入crypto模块
const crypto = require('crypto');
// 定义密钥和初始化向量(IV)
const secretKey = 'thisisaverysecretkey123'; // 密钥长度需要符合AES要求,如16, 24, 或32字节
const iv = crypto.randomBytes(16); // 初始化向量,长度为16字节
// 加密函数
function encrypt(text) {
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secretKey), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
// 解密函数
function decrypt(text) {
let textParts = text.split(':');
let iv = Buffer.from(textParts.shift(), 'hex');
let encryptedText = Buffer.from(textParts.join(':'), 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(secretKey), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
// 示例用法
let originalText = 'Hello, World!';
let encryptedText = encrypt(originalText);
console.log('Encrypted:', encryptedText);
let decryptedText = decrypt(encryptedText);
console.log('Decrypted:', decryptedText);
crypto 模块:这是 Node.js 内置的用于加密操作的模块。secretKey 是用于加密和解密的密钥,长度必须符合 AES 的要求(16, 24, 或 32 字节)。iv 是初始化向量,长度为 16 字节,确保相同的明文在不同的加密过程中产生不同的密文。encrypt:crypto.createCipheriv 创建一个加密器,指定算法为 aes-256-cbc。decrypt:crypto.createDecipheriv 创建一个解密器,将加密后的文本还原为原始文本。请注意,这段代码适用于 Node.js 环境。如果你在浏览器环境中使用 JavaScript,你需要使用其他库(如 CryptoJS)来实现类似的功能。
上一篇:js parse
下一篇:js des加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站