Node.js crypto模块所有 API 详解 + 常用 API + 使用场景

一、crypto 模块 API 分类详解

先引入模块:

javascript 复制代码
const crypto = require('crypto');

1. 哈希 (Hash)

用于不可逆的数据摘要(密码存储、数据完整性校验)。

  • crypto.createHash(algorithm[, options])

    创建一个 Hash 对象。常见算法:sha256, sha512, md5(不安全,不推荐)。

    javascript 复制代码
    const hash = crypto.createHash('sha256')
      .update('hello')
      .digest('hex');
    console.log(hash);
  • 常用方法:

    • .update(data[, inputEncoding]) → 添加要哈希的数据

    • .digest([encoding]) → 计算结果并返回(hex/base64/buffer)


2. HMAC (基于密钥的哈希)

常用于签名、请求认证(例如 API 签名)。

  • crypto.createHmac(algorithm, key[, options])

    javascript 复制代码
    const hmac = crypto.createHmac('sha256', 'secret')
      .update('message')
      .digest('hex');
    console.log(hmac);

3. 对称加密 (Cipher / Decipher)

同一个密钥进行加密解密,常用于数据存储。

  • 加密:crypto.createCipheriv(algorithm, key, iv[, options])

  • 解密:crypto.createDecipheriv(algorithm, key, iv[, options])

常见算法:aes-256-cbc, aes-192-gcm 等。

javascript 复制代码
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 256位密钥
const iv = crypto.randomBytes(16);  // 初始化向量

// 加密
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello World', 'utf8', 'hex');
encrypted += cipher.final('hex');

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

console.log({ encrypted, decrypted });

4. 非对称加密 (RSA, EC 等)

用于安全传输(加密/解密)、数字签名/验签。

(1) 密钥对生成

  • crypto.generateKeyPair(type, options, callback)

  • crypto.generateKeyPairSync(type, options)

javascript 复制代码
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

(2) 加密/解密

  • crypto.publicEncrypt(key, buffer)

  • crypto.privateDecrypt(key, buffer)

javascript 复制代码
const message = Buffer.from('Secret Message');
const encrypted = crypto.publicEncrypt(publicKey, message);
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log(decrypted.toString());

(3) 签名/验证

  • crypto.createSign(algorithm[, options])

  • crypto.createVerify(algorithm[, options])

javascript 复制代码
// 签名
const sign = crypto.createSign('sha256');
sign.update('data');
const signature = sign.sign(privateKey, 'hex');

// 验证
const verify = crypto.createVerify('sha256');
verify.update('data');
console.log(verify.verify(publicKey, signature, 'hex'));

5. 密钥派生 (KDF)

常用于用户密码 → 派生加密密钥。

  • crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)

  • crypto.scrypt(password, salt, keylen[, options], callback)

javascript 复制代码
crypto.scrypt('password', 'salt', 32, (err, key) => {
  console.log('Derived key:', key.toString('hex'));
});

6. 随机数 (安全随机)

  • crypto.randomBytes(size[, callback]) → 生成随机字节

  • crypto.randomInt(min, max[, callback]) → 生成随机整数

javascript 复制代码
console.log(crypto.randomBytes(16).toString('hex'));
console.log(crypto.randomInt(1, 100));

7. Diffie-Hellman (密钥交换)

用于安全地生成共享密钥(如 TLS 协议)。

  • crypto.createDiffieHellman(primeLength[, generator])

  • crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])

javascript 复制代码
const alice = crypto.createDiffieHellman(2048);
const aliceKey = alice.generateKeys();

const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();

const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
console.log(aliceSecret.equals(bobSecret)); // true

8. KeyObject (密钥对象管理)

  • crypto.createSecretKey(buffer[, encoding])

  • crypto.createPublicKey(key)

  • crypto.createPrivateKey(key)

javascript 复制代码
const secret = crypto.createSecretKey(crypto.randomBytes(32));
console.log(secret.type); // 'secret'

9. X509 / PEM / DER 证书操作

  • crypto.X509Certificate → 解析证书

  • crypto.Certificate(旧 API,已废弃)


二、常用 API 总结

最常用的 API 是:

  1. 哈希

    • crypto.createHash('sha256')
  2. HMAC

    • crypto.createHmac('sha256', key)
  3. 对称加密

    • crypto.createCipheriv / crypto.createDecipheriv
  4. 非对称加密

    • crypto.generateKeyPairSync

    • crypto.publicEncrypt / crypto.privateDecrypt

    • crypto.createSign / crypto.createVerify

  5. 密码学安全随机数

    • crypto.randomBytes

    • crypto.randomInt

  6. 密码学派生

    • crypto.scrypt / crypto.pbkdf2

三、使用场景总结

场景 常用 API 示例
密码存储 scrypt / pbkdf2 + randomBytes 数据库存储用户密码时使用安全散列加盐
数据完整性校验 createHash 文件下载校验 SHA256
请求签名(API 鉴权) createHmac 类似 AWS 签名机制
敏感信息加密存储 createCipheriv / createDecipheriv 数据库存储银行卡号
安全通信 publicEncrypt / privateDecrypt 前后端传输敏感数据
数字签名 / 证书认证 createSign / createVerify JWT 签名、SSL 证书
密钥交换 createDiffieHellman 两方协商对称加密密钥
随机数生成 randomBytes / randomInt 生成安全 Token、验证码

✅ 总结:

  • crypto 模块是 Node.js 的安全基石。

  • 常用功能:哈希、HMAC、对称加密、非对称加密、签名验签、密钥派生、随机数、证书解析

  • 使用场景覆盖:密码存储、API 鉴权、安全通信、数据保护、数字签名、随机令牌生成

安全注意事项

  1. 算法选择:避免 md5sha1aes-128-ecb 等不安全算法。
  2. 密钥管理:密钥 / 私钥需安全存储(如环境变量、密钥管理服务),禁止硬编码。
  3. 参数合规:IV、盐需随机生成(每个加密 / 哈希单独生成),长度符合算法要求(如 AES 的 IV 为 16 字节)。
  4. 优先异步:加密 / 哈希操作耗时较长时,优先使用异步 API(如 pbkdf2 而非 pbkdf2Sync),避免阻塞事件循环。
相关推荐
Dave.B8 分钟前
vtkPolyDataConnectivityFilter 实用指南
算法·vtk
细节处有神明37 分钟前
开源数据之历史气象数据的获取与使用
人工智能·python·算法
小白开始进步1 小时前
JAKA Zu12 机械臂运动学算法深度解析(含可视化方案)
python·算法·numpy
梵刹古音1 小时前
【C语言】 递归函数
c语言·数据结构·算法
yongui478341 小时前
混凝土二维随机骨料模型 MATLAB 实现
算法·matlab
酉鬼女又兒1 小时前
JAVA牛客入门11~20
算法
代码游侠2 小时前
C语言核心概念复习(二)
c语言·开发语言·数据结构·笔记·学习·算法
XX風2 小时前
2.1_binary_search_tree
算法·计算机视觉
不想写bug呀2 小时前
买卖股票问题
算法·买卖股票问题