Lesson 201 of 296
Password hashing
What you will learn
- Why passwords are never stored or encrypted
- Hashing vs encryption
- Salts and why fast hashes are dangerous
- Argon2id, bcrypt and scrypt
- Implementing hashing and verification
- Password rules and other login protections
On this page
Never store passwords
If your database leaks (it happens to big companies), stored passwords would expose users everywhere, because people reuse passwords. So we never store the password itself, and we do not encrypt it either.
| Encryption | Hashing | |
|---|---|---|
| Reversible? | Yes, with the key | No: one-way |
| Use for | Data you must read back (Lesson 265) | Passwords: you only need to check them |
At login, you hash the entered password the same way and compare the results.
Salt
If two users choose "Password123", the same hash function gives the same hash: attackers could spot shared passwords and use precomputed tables (rainbow tables) of common password hashes. A salt is a random value per user, stored with the hash and mixed into it. Equal passwords then produce different hashes, and precomputed tables become useless.
Why not SHA-256?
SHA-256 and MD5 are fast by design: a graphics card can try billions of guesses per second against a stolen hash. Password hashing needs functions that are deliberately slow and memory-hard (they need lots of memory, which makes graphics-card attacks expensive), with an adjustable cost you raise as hardware improves.
| Algorithm | Notes |
|---|---|
| Argon2id | Winner of the Password Hashing Competition. First choice in OWASP guidance. Memory-hard. Use the argon2 npm package |
| scrypt | Memory-hard; built into Node.js (crypto.scrypt) |
| bcrypt | Older and very widely used; still acceptable. Limits input to 72 bytes |
| PBKDF2 | Acceptable when FIPS compliance is required, with a very high iteration count |
| MD5, SHA-1, SHA-256 alone | Never for passwords |
An implementation with scrypt (built into Node.js)
import { scrypt, randomBytes, timingSafeEqual } from "node:crypto";
const KEY_LENGTH = 64;
const COST = 2 ** 15;
const BLOCK_SIZE = 8;
const PARALLELISM = 1;
function scryptAsync(password: string, salt: Buffer, N: number, r: number, p: number): Promise<Buffer> {
return new Promise((resolve, reject) => {
scrypt(password.normalize("NFKC"), salt, KEY_LENGTH, { N, r, p, maxmem: 128 * N * r * 2 }, (err, key) =>
err ? reject(err) : resolve(key)
);
});
}
export async function hashPassword(password: string): Promise<string> {
const salt = randomBytes(16);
const key = await scryptAsync(password, salt, COST, BLOCK_SIZE, PARALLELISM);
return ["scrypt", COST, BLOCK_SIZE, PARALLELISM, salt.toString("base64"), key.toString("base64")].join("$");
}
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
const [algorithm, n, r, p, saltB64, keyB64] = stored.split("$");
if (algorithm !== "scrypt" || !n || !r || !p || !saltB64 || !keyB64) return false;
const expected = Buffer.from(keyB64, "base64");
const actual = await scryptAsync(password, Buffer.from(saltB64, "base64"), Number(n), Number(r), Number(p));
return actual.length === expected.length && timingSafeEqual(actual, expected);
}Points interviewers look for:
- The async version runs in the libuv thread pool (Lesson 189), so hashing does not block the event loop.
- The stored string includes the algorithm, parameters and salt, so you can raise the cost later and still verify old hashes (then re-hash on the user's next successful login).
timingSafeEqualcompares in constant time, so an attacker cannot learn how many bytes matched from response timing (a timing attack).normalize("NFKC")makes visually identical Unicode passwords hash the same (Lesson 33).- With the
argon2package the code is justawait argon2.hash(password)andawait argon2.verify(hash, password); it handles salt and parameters for you.
Password rules (modern guidance)
Current UK NCSC and US NIST guidance:
- Require a minimum length (at least 8, better 12 or more), allow long passwords and passphrases (up to at least 64 characters), allow all characters including spaces.
- Do not force arbitrary complexity rules ("one capital, one symbol") or regular expiry; they make people choose worse passwords.
- Check against known breached passwords (for example the Have I Been Pwned "Pwned Passwords" API, which uses k-anonymity so the full password hash never leaves your server).
- Offer multi-factor authentication and passkeys (WebAuthn): passkeys use public-key cryptography, cannot be phished and need no password at all.
Protecting the login endpoint
- Rate limit attempts per account and per IP (Lesson 238), with growing delays or temporary lockout.
- Same error message for "unknown email" and "wrong password" ("Email or password is incorrect") to avoid revealing which emails are registered. Ideally take the same time in both cases (hash a dummy password when the user does not exist).
- Password reset: a random, single-use, short-lived token sent by email; store only a hash of the token; invalidate sessions after a reset.
- Never log passwords (watch request-body logging).
How to say it in an interview
"Passwords are hashed, never stored or encrypted, because hashing is one-way and we only need to check them. Each password gets a random salt so equal passwords differ and rainbow tables are useless, and I use a slow, memory-hard algorithm: Argon2id first, or scrypt or bcrypt, never plain SHA-256, which is fast enough for billions of guesses per second. The stored string includes the parameters so I can raise the cost later, I use the async API so the event loop is not blocked, and I compare with timingSafeEqual. Around it I follow NCSC and NIST guidance on length and breached-password checks, rate limit logins, use generic error messages, and offer MFA and passkeys."
Key words
| Word | Meaning |
|---|---|
| Hash | A one-way fingerprint of data |
| Salt | A random value per password mixed into the hash |
| Rainbow table | Precomputed hashes of common passwords |
| Argon2id / scrypt / bcrypt | Slow, purpose-built password hashing algorithms |
| Memory-hard | Needs lots of memory, making mass guessing expensive |
| Timing attack | Learning secrets from how long operations take |
| Passkey | Password-less login using public-key cryptography (WebAuthn) |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.