Full answer
A fast hash such as SHA-256 lets an attacker who steals the database test billions of guesses per second. Password hashing functions are slow and memory-hungry on purpose, and they use a random salt, so equal passwords give different hashes and precomputed tables (rainbow tables) are useless.
Node has crypto.scrypt built in. Steps:
- Create a random salt of at least 16 bytes with crypto.randomBytes.
- Derive a key with scrypt(password, salt, 64). The async version uses the libuv thread pool, so it does not block the event loop (the sync version does).
- Store algorithm, parameters, salt and hash together, for example scrypt$N$salt$hash, so you can change the settings later and re-hash on login.
- To check a login, derive the key with the stored salt and compare using crypto.timingSafeEqual. A normal === comparison stops at the first different byte, and response time can leak how many bytes matched. timingSafeEqual takes the same time for equal-length inputs and throws if the lengths differ, so compare lengths first.
Related rules:
- Use crypto.randomBytes or crypto.randomUUID for tokens. Math.random is predictable.
- Do not put secrets in source code, logs or client bundles. Read them from process.env, or a secret manager, and rotate them.
- Rate-limit login attempts and use multi-factor authentication for important accounts.
- Because scrypt uses the thread pool, a flood of logins can saturate it. Limit the concurrency.
const crypto = require('node:crypto');
const { promisify } = require('node:util');
const scrypt = promisify(crypto.scrypt);
async function hashPassword(password) {
const salt = crypto.randomBytes(16);
const key = await scrypt(password, salt, 64);
return `scrypt$${salt.toString('hex')}$${key.toString('hex')}`;
}
async function verifyPassword(password, stored) {
const [, saltHex, keyHex] = stored.split('$');
const expected = Buffer.from(keyHex, 'hex');
const actual = await scrypt(password, Buffer.from(saltHex, 'hex'), expected.length);
return actual.length === expected.length && crypto.timingSafeEqual(actual, expected);
}
async function main() {
const first = await hashPassword('correct horse battery staple');
const second = await hashPassword('correct horse battery staple');
console.log('stored format has 3 parts:', first.split('$').length === 3);
console.log('same password, different hashes:', first !== second);
console.log('correct password accepted:', await verifyPassword('correct horse battery staple', first));
console.log('wrong password rejected: ', !(await verifyPassword('wrong password', first)));
const token = crypto.randomBytes(32).toString('base64url');
console.log('random token length (43 chars for 32 bytes):', token.length);
}
main();The default scrypt cost is acceptable for learning. For production, follow current guidance for the cost parameters and test the time per hash on your hardware. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): stored format has 3 parts: true same password, different hashes: true correct password accepted: true wrong password rejected: true random token length (43 chars for 32 bytes): 43
Key points
- Slow, salted hashes: scrypt, argon2 or bcrypt.
- Store salt and parameters with the hash.
- Compare with timingSafeEqual.
- Use randomBytes for tokens, never Math.random.
- Keep secrets out of code and logs.
Common mistakes
- Hashing passwords with SHA-256 or MD5.
- Using one global salt for all users.
- Comparing hashes with ===.
- Using Math.random for reset tokens.
Follow-ups
- How would you upgrade the cost parameters later without forcing a reset?
- Why is the async scrypt better than the sync version in a server?
- How do you protect against credential stuffing?
Tips
- Explain salt and slowness in one sentence each.
- Mention timing attacks, because it separates good answers from average ones.
- State that tokens come from a cryptographic random source.