4 min read
•Question 31 of 62mediumHow to use the Crypto module in Node.js?
Hashing, encryption, and cryptographic operations.
What You'll Learn
- Hashing passwords
- Encryption/Decryption
- Random bytes generation
Hashing
code.jsJavaScript
const crypto = require('crypto');
// Simple hash
const hash = crypto.createHash('sha256')
.update('password')
.digest('hex');
// Hash with salt (for passwords)
const salt = crypto.randomBytes(16).toString('hex');
const hashedPassword = crypto.pbkdf2Sync(
'password', salt, 1000, 64, 'sha512'
).toString('hex');Password Hashing (Recommended)
code.jsJavaScript
const crypto = require('crypto');
function hashPassword(password) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.scryptSync(password, salt, 64).toString('hex');
return `${salt}:${hash}`;
}
function verifyPassword(password, stored) {
const [salt, hash] = stored.split(':');
const newHash = crypto.scryptSync(password, salt, 64).toString('hex');
return hash === newHash;
}Encryption/Decryption
code.jsJavaScript
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
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 encrypted;
}
function decrypt(encrypted) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}Random Values
code.jsJavaScript
// Random bytes
const bytes = crypto.randomBytes(32);
// Random UUID
const uuid = crypto.randomUUID();