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),避免阻塞事件循环。
相关推荐
八个程序员4 分钟前
自定义函数(C++)
开发语言·c++·算法
ad钙奶长高高10 分钟前
【C语言】初始C语言
c语言·开发语言·算法
罗西的思考15 分钟前
【Agent】 ACE(Agentic Context Engineering)源码阅读笔记---(3)关键创新
人工智能·算法
报错小能手1 小时前
C++笔记(面向对象)静态联编和动态联编
开发语言·c++·算法
WBluuue2 小时前
AtCoder Beginner Contest 430(ABCDEF)
c++·算法
小肖爱笑不爱笑2 小时前
2025/11/5 IO流(字节流、字符流、字节缓冲流、字符缓冲流) 计算机存储规则(ASCII、GBK、Unicode)
java·开发语言·算法
熬了夜的程序员2 小时前
【LeetCode】99. 恢复二叉搜索树
算法·leetcode·职场和发展
Kent_J_Truman2 小时前
LeetCode Hot100 自用
算法·leetcode·职场和发展
还是码字踏实2 小时前
算法题种类与解题思路全面指南:基于LeetCode Hot 100与牛客Top 101
算法·leetcode
Victory_orsh3 小时前
“自然搞懂”深度学习(基于Pytorch架构)——010203
人工智能·pytorch·python·深度学习·神经网络·算法·机器学习