Core Modules
Node.js crypto Module
The crypto module provides hashing, HMACs, encryption and secure random values. For password storage specifically, use a deliberately slow algorithm such as scrypt or bcrypt rather than a fast hash.
What is crypto Module in Node.js?
The crypto module provides hashing, HMACs, encryption and secure random values. For password storage specifically, use a deliberately slow algorithm such as scrypt or bcrypt rather than a fast hash.
crypto Module example
JavaScript
import crypto from 'node:crypto';
// content hash — NOT for passwords
crypto.createHash('sha256').update('data').digest('hex');
// cryptographically secure random token
const token = crypto.randomBytes(32).toString('hex');
const id = crypto.randomUUID();
// password hashing with a per-user salt
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.scryptSync('userPassword', salt, 64).toString('hex');
// constant-time comparison prevents timing attacks
crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));Key points to remember
- SHA-256 is for integrity, never for passwords — it is far too fast to resist brute force.
- Use bcrypt, argon2 or scrypt for passwords, always with a unique salt.
- Never use Math.random() for tokens, session ids or OTPs.
- Compare secrets with timingSafeEqual, not ===.
Common mistakes with crypto Module
- Storing MD5 or SHA-1 password hashes, which are trivially cracked.
- Reusing one salt for every user.
Node.js crypto Module— Interview Questions & FAQs
How should I hash passwords in Node.js?+
With bcrypt, argon2 or crypto.scrypt, each with a unique random salt per user. These are intentionally slow, which is what makes brute-force attacks impractical. Never use SHA-256 or MD5 for passwords.
