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),避免阻塞事件循环。
相关推荐
StarPrayers.6 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
爱吃橘的橘猫6 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式
235166 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
weixin_307779137 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
柳安忆7 小时前
【论文阅读】Sparks of Science
算法
web安全工具库7 小时前
从课堂笔记到实践:深入理解Linux C函数库的奥秘
java·数据库·算法
爱编程的鱼9 小时前
C# 变量详解:从基础概念到高级应用
java·算法·c#
HalvmånEver9 小时前
红黑树实现与原理剖析(上篇):核心规则与插入平衡逻辑
数据结构·c++·学习·算法·红黑树
青灬河9 小时前
实现企业级全栈应用服务框架-Elpis(一)
vue.js·node.js