全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-15 10 分钟 ✍️ juanwangdev

Node.js 加密与安全 (crypto)

crypto 模块提供 OpenSSL 封装,支持哈希、加密、签名等安全操作。

哈希算法

创建哈希

JavaScript
const crypto = require('crypto');

// MD5 哈希
const md5 = crypto.createHash('md5')
  .update('hello world')
  .digest('hex');
console.log(md5); // 5eb63bbbe01eeed093cb22bb8f5acdc3

// SHA256 哈希
const sha256 = crypto.createHash('sha256')
  .update('hello world')
  .digest('hex');
console.log(sha256);

常用哈希算法

算法输出长度用途
MD5128 bit校验(不推荐安全场景)
SHA-1160 bit已不安全
SHA-256256 bit推荐
SHA-512512 bit高安全需求

HMAC 消息认证

JavaScript
const hmac = crypto.createHmac('sha256', 'secret-key')
  .update('message')
  .digest('hex');
console.log(hmac);

对称加密

AES 加密解密

JavaScript
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 密钥
const iv = crypto.randomBytes(16);  // 初始化向量

// 加密
function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

// 解密
function decrypt(encrypted) {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

const encrypted = encrypt('敏感数据');
console.log('加密:', encrypted);
console.log('解密:', decrypt(encrypted));

非对称加密

RSA 密钥对生成

JavaScript
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

// 导出 PEM 格式
console.log(publicKey.export({ type: 'spki', format: 'pem' }));
console.log(privateKey.export({ type: 'pkcs8', format: 'pem' }));

RSA 加密解密

JavaScript
const data = '敏感数据';

// 公钥加密
const encrypted = crypto.publicEncrypt(
  { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
  Buffer.from(data)
);

// 私钥解密
const decrypted = crypto.privateDecrypt(
  { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
  encrypted
);

console.log(decrypted.toString());

数字签名

JavaScript
const data = '要签名的数据';

// 私钥签名
const sign = crypto.createSign('SHA256');
sign.update(data);
const signature = sign.sign(privateKey, 'hex');

// 公钥验证
const verify = crypto.createVerify('SHA256');
verify.update(data);
const isValid = verify.verify(publicKey, signature, 'hex');

console.log('签名有效:', isValid);

密码存储

JavaScript
const crypto = require('crypto');

function hashPassword(password, salt) {
  return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512')
    .toString('hex');
}

const salt = crypto.randomBytes(16).toString('hex');
const hashed = hashPassword('用户密码', salt);

// 存储时保存 salt 和 hashed

随机数生成

JavaScript
// 伪随机
const randomBytes = crypto.randomBytes(16);
console.log(randomBytes.toString('hex'));

// 整数范围
const randomInt = crypto.randomInt(1, 100);
console.log(randomInt);

注意事项

  • MD5/SHA-1 不安全,仅用于数据校验
  • AES 密钥长度必须符合算法要求(16/24/32 字节)
  • RSA 推荐 2048 位以上密钥
  • 密码存储使用 bcrypt 或 pbkdf2,不要明文或简单哈希

要点总结

  • createHash() 创建哈希,推荐 SHA-256
  • createCipheriv() 对称加密,需保管密钥和 IV
  • publicEncrypt/privateDecrypt RSA 非对称加密
  • createSign/createVerify 实现数字签名
  • pbkdf2 或 bcrypt 安全存储密码

📝 发现内容有误?点击此处直接编辑

← 上一篇 Node.js Buffer 和流
下一篇 → Node.js 进程与 child_process
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库