How to use the Crypto module in Node.js for hashing and encryption?
The Crypto Module
The built-in crypto module provides cryptographic functionality for hashing, encryption, decryption, and generating random values. It's essential for security-sensitive operations.
Hashing (One-way)
Hashing converts data into a fixed-size string. It's irreversible — you cannot get the original data back.
js
const crypto = require('crypto');
// Simple hash
const hash = crypto.createHash('sha256')
.update('Hello World')
.digest('hex');
console.log(hash);
// a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146eCommon Hash Algorithms
| Algorithm | Output Size | Use Case |
|---|---|---|
md5 | 128-bit | Checksums (NOT for passwords) |
sha256 | 256-bit | Data integrity, signatures |
sha512 | 512-bit | Higher security needs |
Password Hashing with Salt
js
function hashPassword(password) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
return { salt, hash };
}
function verifyPassword(password, salt, hash) {
const verify = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
return verify === hash;
}
const { salt, hash } = hashPassword('myPassword123');
console.log(verifyPassword('myPassword123', salt, hash)); // true
console.log(verifyPassword('wrongPassword', salt, hash)); // falseSymmetric Encryption (AES)
Same key for encryption and decryption:
js
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 { iv: iv.toString('hex'), encrypted };
}
function decrypt(encrypted, ivHex) {
const decipher = crypto.createDecipheriv(
algorithm,
key,
Buffer.from(ivHex, 'hex')
);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const { iv: ivHex, encrypted } = encrypt('Secret message');
console.log('Encrypted:', encrypted);
console.log('Decrypted:', decrypt(encrypted, ivHex));HMAC (Hash-based Message Authentication Code)
Verifies both data integrity and authenticity:
js
const secret = 'my-secret-key';
const hmac = crypto.createHmac('sha256', secret)
.update('data to verify')
.digest('hex');
// Verify
function verifyHmac(data, receivedHmac, secret) {
const expected = crypto.createHmac('sha256', secret)
.update(data)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(receivedHmac),
Buffer.from(expected)
);
}Generating Random Values
js
// Random bytes (for tokens, keys, salts)
const token = crypto.randomBytes(32).toString('hex');
// Random UUID
const uuid = crypto.randomUUID();
// Random integer in range
const randomInt = crypto.randomInt(1, 100);Quick Reference
| Operation | Method | Use Case |
|---|---|---|
| Hash | createHash() | Checksums, data fingerprints |
| Password hash | pbkdf2 / scrypt | Password storage |
| Encrypt/Decrypt | createCipheriv() | Sensitive data at rest |
| HMAC | createHmac() | API signatures, webhooks |
| Random bytes | randomBytes() | Tokens, salts, keys |
| UUID | randomUUID() | Unique identifiers |
Important: Never use
md5orsha1for passwords. Usepbkdf2,scrypt, orbcryptwith proper salt and iteration count. Always usetimingSafeEqual()for comparing hashes to prevent timing attacks.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.