Password Storage
Storing passwords safely — why encryption and fast hashes fail, salts, rainbow tables, slow password hashing (Argon2id, bcrypt, scrypt, PBKDF2) and tuning work factors, peppers, rehashing on login, breach checks, and moving beyond passwords.
Databases get breached — through SQL injection, leaked backups, insiders or compromised cloud credentials. When that happens, how passwords were stored decides whether attackers get a list of useless hashes or millions of working credentials, which people reuse on their email and bank accounts.
What not to do
| Approach | Why it fails |
|---|---|
| Plain text | Anyone with database access sees every password. Still found in breaches. |
| Encryption | Reversible: the key usually lives next to the database and leaks with it. Passwords never need to be decrypted — only checked. |
| Fast hash (MD5, SHA-1, SHA-256) | GPUs compute billions of SHA-256 hashes per second; most human passwords fall to dictionary and rule-based guessing in minutes |
| Unsalted hash | Identical passwords produce identical hashes, and precomputed tables crack them instantly |
Salts
A salt is a unique random value (16+ bytes) generated per user and stored alongside the hash:
hash = PasswordHash(password, salt)
stored: user_id | salt | hashSalts defeat:
- Rainbow tables — huge precomputed hash → password lookup tables are useless when every hash has a different salt.
- Identical-password detection — two users with "Summer2026!" get different hashes.
- Batch cracking — each guess must be hashed separately for each user, multiplying the attacker's work by the number of users.
Salts are not secret. They don't make a single weak password harder to guess — that's what slowness is for.
Slow, memory-hard password hashing
Password hashing functions are deliberately expensive, with a tunable work factor. Making one verification take ~0.1–0.5 s is unnoticeable at login but devastating for an attacker trying billions of guesses.
| Algorithm | Notes | Recommended settings (OWASP-style baseline) |
|---|---|---|
| Argon2id | Winner of the Password Hashing Competition (2015); memory-hard — each guess needs lots of RAM, blunting GPUs and ASICs | m = 19–64 MiB, t = 2–3 iterations, p = 1 |
| scrypt | Memory-hard; used by some systems and cryptocurrencies | N = 2¹⁷, r = 8, p = 1 |
| bcrypt | Battle-tested since 1999; built in to many frameworks; inputs truncated at 72 bytes | cost ≥ 10–12 |
| PBKDF2 | NIST-approved, needed for FIPS compliance; not memory-hard | ≥ 600,000 iterations with HMAC-SHA256 |
Prefer Argon2id; bcrypt is fine where it's the framework default. Benchmark on your production hardware and pick the highest cost your login latency and capacity allow — and raise it over time.
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher(time_cost=3, memory_cost=64 * 1024, parallelism=1) # 64 MiB
stored = ph.hash("correct horse battery staple")
# '$argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>' — algorithm, parameters and salt are encoded inside
def login(user, password):
try:
ph.verify(user.password_hash, password)
except VerifyMismatchError:
return False
if ph.check_needs_rehash(user.password_hash): # parameters were upgraded since
user.password_hash = ph.hash(password) # transparently rehash with new settings
user.save()
return True// Node.js with bcrypt
import bcrypt from "bcrypt";
const hash = await bcrypt.hash(password, 12); // salt generated and embedded
const ok = await bcrypt.compare(attempt, hash); // constant-timeThe encoded format ($argon2id$…, $2b$12$…) stores the algorithm, parameters and salt with the hash, so you can upgrade parameters or algorithms gradually: verify with the old format, rehash with the new one on successful login.
Peppers
A pepper is a secret value not stored in the database — kept in a secrets manager or HSM — and mixed in (e.g. HMAC(pepper, password) before hashing, or encrypting the hashes). If only the database leaks, hashes can't be cracked at all without the pepper. It adds operational complexity (rotation requires care), so it's defence in depth, not a substitute for a proper password hash.
Beyond the hash: the rest of the system
- Rate limiting and lockouts on login, per account and per IP, plus CAPTCHAs after failures — online guessing is slower than offline cracking, but credential stuffing is massive (Rate limiting).
- Breached-password checks: reject passwords found in known breaches using Have I Been Pwned's k-anonymity API (send only the first 5 hex characters of the SHA-1; compare suffixes locally).
- Sensible password policy (NIST SP 800-63B): minimum length (at least 8, encourage 15+), allow long passphrases and all characters, no forced composition rules or periodic resets (they make passwords worse), support password managers and paste.
- Never log passwords — watch request logging, error trackers and analytics.
- TLS everywhere, so passwords aren't exposed in transit.
- Constant-time verification and identical error messages to avoid user enumeration.
- Secure password reset: single-use, short-lived, high-entropy tokens (store only their hashes), sent to verified channels.
- Multi-factor authentication, and ideally passkeys — public-key credentials that eliminate shared secrets on the server entirely (Authentication).
Related: key derivation from passwords
When a password must become an encryption key (password managers, encrypted archives, disk encryption), use the same slow functions as KDFs: Argon2id or scrypt (or PBKDF2) with a random salt, producing a key for an AEAD. A weak password still yields a weak key — the KDF only slows guessing down.
- Never store plain text, encrypted, or fast-hashed passwords.
- Use a unique random salt per password to defeat rainbow tables and batch cracking.
- Use slow, tunable password hashing: Argon2id preferred; bcrypt or scrypt fine; PBKDF2 for FIPS.
- Encode parameters with the hash and rehash on login to upgrade over time.
- A pepper held outside the database adds defence in depth.
- Combine with rate limiting, breached-password checks, NIST-style policies, MFA and passkeys.
QHow should you store user passwords?medium
Hash them with a slow, salted password hashing function — Argon2id preferably, or bcrypt or scrypt, or PBKDF2 with many iterations where FIPS is required — using a unique random salt per user and a work factor tuned to roughly a few hundred milliseconds on production hardware. Store the encoded string containing the algorithm, parameters, salt and hash, verify with the library's constant-time check, and rehash when parameters change. Never use encryption or a fast hash like SHA-256. Add rate limiting, breached-password checks and MFA, and optionally a pepper kept in a secrets manager.