```html
Node.js 中的密码学:使用
1. 导入
Node.js 中的密码学:使用 crypto 模块进行加密和哈希
数据安全是现代 Web 开发的关键方面之一。在 Node.js 中,内置的 crypto 模块提供了强大的密码学保护工具:从密码哈希到非对称加密。在本文中,我们将详细分析 crypto 模块的主要功能,学习如何加密和解密数据,以及如何使用哈希安全地存储密码。
1. 导入 crypto 模块
crypto 模块是内置的,因此不需要安装额外的包。它通过标准方式导入:
const crypto = require('crypto');2. 数据哈希
哈希是将任意长度的数据转换为固定长度字符串的过程。与加密不同,哈希函数是不可逆的。最流行的算法有:SHA-256、SHA-512。
示例:使用 SHA-256 对字符串进行哈希
const data = 'PythonLib — ваш путеводитель в мир IT';const hash = crypto.createHash('sha256').update(data).digest('hex');console.log('SHA-256 哈希:', hash);示例:加盐哈希 (bcrypt)
为了安全存储密码,建议使用 bcrypt 或 scrypt 算法。Node.js 内置支持 scrypt:
const password = 'mySuperPassword123';const salt = crypto.randomBytes(16).toString('hex');
crypto.scrypt(password, salt, 64, (err, derivedKey) => { if (err) throw err; console.log('密码哈希:', derivedKey.toString('hex'));});3. 对称加密 (AES)
对称加密使用相同的密钥来加密和解密数据。最常见的算法是 AES(高级加密标准)。
使用 AES-256-CBC 加密数据
const algorithm = 'aes-256-cbc';const key = crypto.randomBytes(32); // 256 位密钥const iv = crypto.randomBytes(16); // 初始化向量
function encrypt(text) { const cipher = crypto.createCipheriv(algorithm, key, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return { iv: iv.toString('hex'), encryptedData: encrypted };}
const originalText = 'Секретные данные для PythonLib';const encrypted = encrypt(originalText);console.log('加密数据:', encrypted);解密数据
function decrypt(encryptedObj) { const decipher = crypto.createDecipheriv( algorithm, key, Buffer.from(encryptedObj.iv, 'hex') ); let decrypted = decipher.update(encryptedObj.encryptedData, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted;}
const decryptedText = decrypt(encrypted);console.log('解密文本:', decryptedText);4. 非对称加密 (RSA)
非对称加密使用一对密钥:公钥和私钥。数据用公钥加密,用私钥解密。这是 HTTPS 和数字签名的基础。
生成 RSA 密钥对
const { generateKeyPairSync } = require('crypto');
const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }});
console.log('公钥:', publicKey);console.log('私钥:', privateKey);使用 RSA 加密和解密
const secretMessage = 'Привет, PythonLib!';
// 使用公钥加密const encryptedData = crypto.publicEncrypt( { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }, Buffer.from(secretMessage));console.log('加密
```