Node.js crypto 模块使用指南
1. 哈希算法
1.1 MD5 哈希(不推荐用于密码存储)
import crypto from 'crypto';
const data = 'Hello, World!';
const md5Hash = crypto.createHash('md5').update(data).digest('hex');
console.log('MD5:', md5Hash); // 示例输出:65a8e27d8879283831b664bd8b7f0ad4
⚠️ 警告:MD5 已不推荐用于密码存储,因其易受碰撞攻击。密码存储应使用bcrypt、scrypt 或 Argon2。
1.2 SHA-256 哈希(可用于数据完整性校验)
import crypto from 'crypto';
const data = 'Hello, World!';
const sha256Hash = crypto.createHash('sha256').update(data).digest('hex');
console.log('SHA-256:', sha256Hash);
// 示例输出:dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
2. HMAC(哈希消息认证码)
import crypto from 'crypto';
const secretKey = 'my_secret_key'; // 密钥需安全存储(如环境变量)
const data = 'Hello, World!';
const hmac = crypto.createHmac('sha256', secretKey)
.update(data)
.digest('hex');
console.log('HMAC:', hmac);
// 示例输出:f3caf5d47e3c8cdea3b3ae8c87b64d247d4dacf783b8d171083679d5329159cc
最佳实践:密钥长度应与哈希算法位数匹配(如 SHA-256 使用 32 字节密钥)。
3. 生成随机值
3.1 异步生成(推荐避免阻塞)
import crypto from 'crypto';
crypto.randomBytes(16, (err, buffer) => {
if (err) throw err;
console.log('Async Random:', buffer.toString('hex'));
});
3.2 同步生成
import crypto from 'crypto';
const randomValue = crypto.randomBytes(16).toString('hex');
console.log('Sync Random:', randomValue); // 示例输出:a3f5d8e2c1b0a9f876543210...
4. 对称加密与解密(AES-256-CBC)
4.1 加密
import crypto from 'crypto';
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 需安全存储密钥
const iv = crypto.randomBytes(16); // 每次加密应使用唯一IV
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('Encrypted:', encrypted);
4.2 解密
import crypto from 'crypto';
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log('Decrypted:', decrypted); // 输出原始明文
5. 非对称加密(RSA 密钥对)
5.1 同步生成密钥对
import crypto from 'crypto';
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048, // 推荐至少 2048 位
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);
5.2 异步生成密钥对
import crypto from 'crypto';
crypto.generateKeyPair('rsa', {
modulusLength: 2048, // 推荐至少 2048 位
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
}, (err, publicKey, privateKey) => {
if (err) throw err;
// 处理密钥...
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);
});
6. 数字签名与验证
6.1 使用私钥签名
import crypto from 'crypto';
const sign = crypto.createSign('SHA256');
sign.update(data);
sign.end();
const signature = sign.sign(privateKey, 'hex');
console.log('Signature:', signature);
6.2 使用公钥验证
import crypto from 'crypto';
const verify = crypto.createVerify('SHA256');
verify.update(data);
verify.end();
const isValid = verify.verify(publicKey, signature, 'hex');
console.log('Signature Valid:', isValid); // true/false