Skip to content

NODE

内置的加密库 crypto

使用 crypto 进行对称加解密

js
const crypto = require('crypto');

// 定义加密密钥和明文
const key = 'my-secret-key';
const plaintext = 'Hello, world!';

// 创建加密器
const cipher = crypto.createCipher('aes-256-cbc', key);

// 加密明文
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');

// 输出加密结果
console.log('Encrypted text: ' + encrypted);

// 创建解密器
const decipher = crypto.createDecipher('aes-256-cbc', key);

// 解密密文
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');

// 输出解密结果
console.log('Decrypted text: ' + decrypted);