当前位置: 首页 > news >正文

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

一、crypto 模块 API 分类详解

先引入模块:

const crypto = require('crypto');

1. 哈希 (Hash)

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

  • crypto.createHash(algorithm[, options])
    创建一个 Hash 对象。常见算法:sha256, sha512, md5(不安全,不推荐)。

    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])

    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 等。

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)

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

(2) 加密/解密

  • crypto.publicEncrypt(key, buffer)

  • crypto.privateDecrypt(key, buffer)

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])

// 签名
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)

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

6. 随机数 (安全随机)

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

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

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])

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)

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 / createVerifyJWT 签名、SSL 证书
密钥交换createDiffieHellman两方协商对称加密密钥
随机数生成randomBytes / randomInt生成安全 Token、验证码

✅ 总结:

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

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

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

安全注意事项

  1. 算法选择:避免 md5sha1aes-128-ecb 等不安全算法。
  2. 密钥管理:密钥 / 私钥需安全存储(如环境变量、密钥管理服务),禁止硬编码。
  3. 参数合规:IV、盐需随机生成(每个加密 / 哈希单独生成),长度符合算法要求(如 AES 的 IV 为 16 字节)。
  4. 优先异步:加密 / 哈希操作耗时较长时,优先使用异步 API(如 pbkdf2 而非 pbkdf2Sync),避免阻塞事件循环。
http://www.dtcms.com/a/478251.html

相关文章:

  • 好文与笔记分享 Paris, A Decentralized Trained Open-Weight Diffusion Model
  • 企业网站托管排版设计专业网络营销外包公司
  • 1.5 欧拉集群安装Memcached缓存服务
  • asp.net 开发的网站wordpress付费下载模板
  • 十三、OpenCV中的图像的向上采样和向下采样
  • 一份面向研究人员的强化学习对齐指南:为自定义语言模型实施与评估 PPO 和 DPO
  • 石家庄网站seo网页设计与制作课程定位
  • Python全栈(基础篇)——Day10:后端内容(map+reduce+filter+sorted+实战演示+每日一题)
  • Datawhale OpenAI官方智能体框架202510
  • 25软件测试工作量估算
  • 网站页脚版权信息在线html编辑
  • 计算机视觉:卷积神经网络(CNN)图像分类从像素与色彩通道基础到特征提取、池化及预测
  • C# 串口通信完整教程 (.NET Framework 4.0)
  • GNN是和RNN一样的吗?多次循环,但是更新的是同一批参数?
  • Ubuntu 24.04 安装 Jenkins
  • 手游做网站推广应该怎么做photoshop做网站
  • 成都专业的整站优化公司起名字免费软件
  • 【threejs】webgl使用effectComposer时的抗锯齿
  • 大语言模型(LLM)领域细分方向解析
  • 简要说明开发网站的步骤谷歌搜索引擎363
  • Spotify(正版流媒体音乐平台) 多语便携版
  • 告别复制粘贴!自动化处理文本空行的新思路
  • 基于「多模态大模型 + BGE向量检索增强RAG」的新能源汽车故障诊断智能问答系统(vue+flask+AI算法)
  • 实战|京东 jd.union.open.goods.search 接口:精准检索与 2025 商业机会挖掘
  • 从零上手 Rokid JSAR:打造专属 AR 桌面交互式 3D魔方,开启空间开发之旅
  • 番禺人才网招聘信恿南昌seo数据监控
  • 自动驾驶强化学习的价值对齐:奖励函数设计的艺术与科学
  • xml 方式声明式事务案例
  • 蓝海国际版网站建设贵阳制作网站
  • MATLAB代码实现了一个双层多尺度动态图卷积网络(DGCN)用于城市交通流量预测,核心功能为模拟生成城市道路网络的交通流量时序数据