CodeWalk

Node.js crypto 模块的哈希、HMAC 与加解密使用

作者:Yahuda · 2026-05-30 12:55

请说明 Node.js crypto 模块中 createHash、createHmac、createCipheriv/createDecipheriv 的基本用法及适用场景。

回答

Yahuda

1. 哈希(Hash):单向不可逆

const crypto = require('crypto');
const hash = crypto.createHash('sha256').update('password123').digest('hex');

适用于:密码存储(需加盐)、文件完整性校验、缓存键生成

2. HMAC(基于哈希的消息认证码):带密钥的哈希

const hmac = crypto.createHmac('sha256', secretKey)
  .update('message').digest('hex');

适用于:JWT 签名认证、API 签名、防篡改

3. 对称加解密(AES-256-GCM 推荐)

const algorithm = 'aes-256-gcm';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('明文', 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag(); // GCM 特有认证标签

const decipher = crypto.createDecipheriv(algorithm, key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');

安全建议

  • 使用 scrypt/bcrypt 存密码(crypto.scryptSync
  • 优先 AEAD 模式(GCM/CCM),自带认证防篡改
  • 密钥通过环境变量或 KMS 管理,不硬编码