以下是一段使用 AES 加密的 JS 代码:

const crypto = require('crypto');

const key = 'mysecretkey'; // 密钥,需要保密
const plaintext = 'Hello, world!'; // 明文

// 加密函数
function encryptAES(plaintext, key) {
  const iv = crypto.randomBytes(16); // 随机生成一个 16 字节的 IV
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv); // 创建加密器
  let ciphertext = cipher.update(plaintext, 'utf8', 'base64'); // 加密明文
  ciphertext += cipher.final('base64');
  return iv.toString('hex') + ':' + ciphertext; // 返回 IV 和密文,用冒号分隔
}

// 解密函数
function decryptAES(ciphertext, key) {
  const [ivHex, encrypted] = ciphertext.split(':'); // 将 IV 和密文分离
  const iv = Buffer.from(ivHex, 'hex');
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); // 创建解密器
  let plaintext = decipher.update(encrypted, 'base64', 'utf8'); // 解密密文
  plaintext += decipher.final('utf8');
  return plaintext; // 返回明文
}

// 测试加密和解密
const ciphertext = encryptAES(plaintext, key);
console.log('密文:', ciphertext);
const decrypted = decryptAES(ciphertext, key);
console.log('明文:', decrypted);

这段代码使用 AES-256-CBC 算法进行加密和解密,采用随机生成的 16 字节 IV 值增加安全性。密钥和明文可以根据需要修改。

写一段 aes 加密的 JS 代码

原文地址: https://www.cveoy.top/t/topic/bbwS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录