Node.js crypto 模块
crypto 模块提供加密和哈希算法,底层由 C/C++ 实现,性能高。
对称加密(AES-256-CBC)
加密和解密使用同一把密钥,速度快,适合大量数据。挑战在于密钥的安全共享。
js
const crypto = require('node:crypto')
// 生成密钥和初始化向量
const key = crypto.randomBytes(32) // 32 字节密钥
const iv = Buffer.from(crypto.randomBytes(16)) // 16 字节 IV
// 加密
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
cipher.update('hello world', 'utf-8', 'hex')
const encrypted = cipher.final('hex')
// 解密
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
decipher.update(encrypted, 'hex')
const decrypted = decipher.final('utf-8')
console.log(decrypted) // 'hello world'非对称加密(RSA)
使用公钥加密、私钥解密。安全性高但速度慢,常用于交换对称密钥。
js
const crypto = require('node:crypto')
// 生成 RSA 密钥对
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
})
// 公钥加密
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from('小满zs'))
// 私钥解密
const decrypted = crypto.privateDecrypt(privateKey, encrypted)
console.log(decrypted.toString()) // '小满zs'哈希函数(MD5 / SHA)
单向不可逆,固定长度输出,输入微小变化导致输出完全不同。
js
const crypto = require('node:crypto')
// MD5
const hash = crypto.createHash('md5')
hash.update('123456')
console.log(hash.digest('hex')) // e10adc3949ba59abbe56e057f20f883e也可用 'sha256' 等更安全的算法。
哈希函数特点:
- 固定长度输出 — 无论输入多大,输出长度固定
- 不可逆 — 无法从哈希值反推原始数据
- 低碰撞概率 — 不同输入几乎不可能产生相同哈希值
常见用途:
- 密码存储(不存明文,只存哈希值)
- 文件完整性校验(上传前后 MD5 比对)