Encryption and hashing
In Node.js development, encryption and hashing are core technologies for ensuring data security. Although often confused, they serve different purposes: encryption is reversible and used to protect sensitive information during transmission, while hashing is irreversible and commonly employed for password storage and data integrity verification.
Fundamentals of Encryption
Node.js provides encryption capabilities through the crypto
module, supporting symmetric encryption (e.g., AES) and asymmetric encryption (e.g., RSA). Symmetric encryption uses the same key for both encryption and decryption, making it suitable for large data volumes. Asymmetric encryption uses public/private key pairs, offering higher security but lower performance.
AES Encryption Example:
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
console.log(encrypt('secret data')); // Output encrypted result
Applications of Hash Functions
Hash functions map data of arbitrary length to fixed-length values and are one-way. In Node.js, commonly used algorithms include SHA-256 and MD5 (not recommended), primarily for password storage and file verification.
Salted Password Hashing Example:
const crypto = require('crypto');
function hashPassword(password, salt) {
return crypto.pbkdf2Sync(
password,
salt,
100000,
64,
'sha512'
).toString('hex');
}
const salt = crypto.randomBytes(32).toString('hex');
console.log(hashPassword('user123', salt)); // Store hash and salt
Key Derivation Functions
PBKDF2, scrypt, and similar algorithms are specifically designed to derive keys from passwords, increasing computational complexity to prevent brute-force attacks. Node.js's crypto.scrypt
implements memory-intensive computations, making it more resistant to ASIC attacks.
scrypt Example:
crypto.scrypt('password', 'salt', 64, { N: 16384 }, (err, derivedKey) => {
console.log(derivedKey.toString('hex'));
});
Message Authentication Codes
HMAC combines hashing with a secret key to verify message integrity and authenticity. It is commonly used in API signature verification scenarios.
HMAC-SHA256 Implementation:
const hmac = crypto.createHmac('sha256', 'secret-key');
hmac.update('data to verify');
console.log(hmac.digest('hex'));
Performance and Security Trade-offs
Encryption operations consume CPU resources. In web servers, consider the following:
- Synchronous APIs block the event loop.
- Adjust PBKDF2 iteration counts to balance security and performance.
- Use
crypto.createCipheriv
instead of the deprecatedcreateCipher
.
Asynchronous Encryption Example:
crypto.pbkdf2('password', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex'));
});
Practical Use Cases
- HTTPS Communication: TLS protocols combine symmetric and asymmetric encryption.
- JWT Tokens: HMAC or RSA signatures verify token validity.
- Database Encryption: Field-level encryption protects user privacy data.
- Blockchain: Hash chains ensure data immutability.
JWT Signature Verification Snippet:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ user: 'admin' }, 'hmac-secret', { algorithm: 'HS256' });
jwt.verify(token, 'hmac-secret', (err, decoded) => {
console.log(decoded); // { user: 'admin' }
});
Common Vulnerability Mitigations
- Weak Hash Algorithms: Avoid MD5/SHA-1; prefer SHA-256/512.
- Salt Reuse: Use unique random salts for each password.
- ECB Mode: Use CBC or GCM modes for AES instead.
- Key Management: Avoid hardcoding keys; use environment variables or key management systems.
Secure Random Number Generation:
// Insecure
Math.random().toString(36).substring(2);
// Secure method
crypto.randomBytes(32).toString('hex');
Node.js Version Differences
Encryption support varies across Node.js versions:
- Starting with v10.0.0, the default iteration count for
pbkdf2
increased from 1,000 to 100,000. - v15.0.0 deprecated
createCipher
/createDecipher
. - v17.0.0 added limited implementation of the Web Crypto API.
Version-Compatible Code:
const { createCipheriv, createDecipheriv } = crypto;
// Replaces deprecated createCipher
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn