Password Storage
Sooner or later, many databases leak. When that happens, the question is whether the attacker gets passwords or only password hashes that are very expensive to guess. Getting this right is one of the most valuable things a developer can do, because people reuse passwords: a leak from your site can unlock their email or bank.
The rules in one table
| Approach | Verdict | Why |
|---|---|---|
| Plain text | Never | One leak exposes every password immediately |
| Encrypted (AES …) | No | Reversible: whoever gets the key gets every password |
| Fast hash (MD5, SHA-1, SHA-256) | No | Guessing is cheap: billions of attempts per second on a GPU |
| Fast hash + salt | Still no | Salts stop precomputed tables, but each guess is still cheap |
| Slow, salted KDF (Argon2id, scrypt, bcrypt, PBKDF2) | Yes | Each guess costs real time and memory |
A KDF (key derivation function) designed for passwords is deliberately slow and has a tunable cost. Your server computes it once per login, which is fine. Someone trying millions of guesses pays that cost millions of times.
Why fast hashes are unsafe
The trouble with SHA-256 is not that it is "broken" (it isn't), but that it is fast. Let's estimate guessing cost with simple arithmetic. Suppose an attacker's hardware can compute 10 billion SHA-256 hashes per second, and users pick from, say, the 100 million most common passwords:
candidates = 100_000_000 # a large list of common passwords
fast_rate = 10_000_000_000 # SHA-256 guesses per second (GPU, rough)
print(f"SHA-256: {candidates / fast_rate:.2f} seconds per hash")
# A slow KDF tuned to take ~50 ms on the server is about a million times slower
# per guess for the attacker too (and memory-hard ones resist GPUs further).
slow_rate = 20 * 1000 # guesses per second across a big GPU rig (rough)
seconds = candidates / slow_rate
print(f"slow KDF: {seconds / 3600:.1f} hours per hash")
users = 1_000_000
print(f"for {users:,} salted users: {seconds * users / (3600 * 24 * 365):,.0f} years")SHA-256: 0.01 seconds per hash
slow KDF: 1.4 hours per hash
for 1,000,000 salted users: 159 years
The numbers are rough, but the shape is the point: a fast hash falls in a fraction of a second; a slow KDF with unique salts turns the same job into something impractical. And truly random, long passwords are out of reach either way.
Salts
A salt is a random value, unique per user, stored next to the hash. It guarantees that two users with the same password get different hashes, and it makes precomputed lookup tables ("rainbow tables") useless, since the attacker would need a separate table per salt. Salts are not secret.
import hashlib
password = b"correct horse"
salt_alice = bytes.fromhex("8f1c2a77d0e94b3a") # DEMO: real salts come from os.urandom(16)
salt_bob = bytes.fromhex("31aa09be5c6d7e21")
print("no salt, alice:", hashlib.sha256(password).hexdigest()[:20])
print("no salt, bob: ", hashlib.sha256(password).hexdigest()[:20])
print("salted, alice: ", hashlib.sha256(salt_alice + password).hexdigest()[:20])
print("salted, bob: ", hashlib.sha256(salt_bob + password).hexdigest()[:20])no salt, alice: 4104d36f8da2c254349f
no salt, bob: 4104d36f8da2c254349f
salted, alice: 41b7bb866c237d1cc02b
salted, bob: c1a6edb9023d786de87e
Salting fixes the "same password, same hash" problem. It doesn't fix speed, which is why we still need a slow KDF.
Hashing passwords with scrypt
scrypt is a memory-hard KDF: each computation needs a configurable amount of RAM, which makes massive GPU guessing expensive. The cryptography package provides it. We store the algorithm, its parameters, the salt and the hash together in one string, so the parameters can be raised later without breaking old records:
import base64
import os
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.exceptions import InvalidKey
N, R, P = 2**14, 8, 1 # cost parameters (production: tune to ~50-100 ms)
def b64(data): return base64.b64encode(data).decode()
def hash_password(password: str) -> str:
salt = os.urandom(16)
kdf = Scrypt(salt=salt, length=32, n=N, r=R, p=P)
key = kdf.derive(password.encode())
return f"scrypt${N}${R}${P}${b64(salt)}${b64(key)}"
def verify_password(password: str, stored: str) -> bool:
_, n, r, p, salt, key = stored.split("quot;)
kdf = Scrypt(salt=base64.b64decode(salt), length=32, n=int(n), r=int(r), p=int(p))
try:
kdf.verify(password.encode(), base64.b64decode(key)) # constant-time check
return True
except InvalidKey:
return False
record = hash_password("correct horse battery staple")
print(record.split("quot;)[:4]) # salt and key change every run, so not printed
print(verify_password("correct horse battery staple", record))
print(verify_password("Correct horse battery staple", record))
print(record != hash_password("correct horse battery staple")) # new salt each time['scrypt', '16384', '8', '1']
True
False
True
kdf.verify recomputes the hash and compares in constant time, like hmac.compare_digest. The last line shows that hashing the same password twice gives different records, because each gets a fresh salt.
PBKDF2
PBKDF2 is older and not memory-hard, but it is FIPS-approved and available everywhere. Its cost is an iteration count; OWASP currently recommends 600,000 iterations for PBKDF2-HMAC-SHA256. With a fixed demo salt the output is deterministic, so you can see the derived key:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def pbkdf2(password: bytes, salt: bytes, iterations: int) -> str:
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=iterations)
return kdf.derive(password).hex()
salt = b"demo-salt-16byte" # DEMO ONLY: use os.urandom(16)
print(pbkdf2(b"hunter2", salt, 1_000)[:32])
print(pbkdf2(b"hunter2", salt, 2_000)[:32]) # different cost, different key
print(pbkdf2(b"hunter3", salt, 1_000)[:32])24f25c59780df4830c510dcfde933dc6
d6eb279f49de196ae5e9966761e73a76
c6b2e78f02cf9c682d7aa58fa03b9b97
(This demo uses small iteration counts so it runs instantly in your browser.)
Practical checklist
- Prefer Argon2id; otherwise scrypt, bcrypt or PBKDF2 with current recommended parameters. Most web frameworks already do this for you (Django uses PBKDF2 by default, with Argon2 available).
- Use a unique random salt per password (the libraries do this automatically).
- Store the algorithm and parameters with each hash, and re-hash on the next successful login when you raise the cost.
- Compare in constant time; never compare hashes with
==. - Optionally add a pepper: a secret key kept outside the database (e.g. HMAC the password with it first), so a database-only leak is not enough.
- Rate-limit logins and support MFA: storage protects leaked data, but online guessing must be stopped at the login form.
Go further: Password Storage: Salts, PBKDF2, scrypt, bcrypt and Argon2id compares all four algorithms and shows how to migrate legacy hashes.
Test yourself
Why is a salted SHA-256 hash still a poor choice for password storage?
- SHA-256 is broken
- It is fast, so each guess is cheap for an attacker
- Salts must be secret
- It produces collisions
What is a salt?
- A secret key stored on another server
- A random, per-user value stored with the hash
- An extra password character
- An encryption algorithm
Why store the algorithm and cost parameters alongside each password hash?
- So users can see them
- So you can verify old hashes and raise the cost later
- It's required by SQL
- To make the hash longer