Salted SHA-256 hashes passwords. Why can a leak still crack them?
Question
An auth service stores passwords as salt_hex + ":" + sha256(salt + password). After a database dump leaks, the team assumes per-user salts keep passwords safe. On modern GPUs, unslowed SHA-256 still computes around 10^10 guesses per second per card.
- Why do per-user salts defeat rainbow tables yet fail against offline GPU cracking?
- Rewrite
hash_passwordandcheck_passwordin Python 3.12 stdlib usinghashlib.scrypt, a 16-byte random salt (secrets.token_bytes), andhmac.compare_digest. - How do you migrate legacy SHA-256 hashes to
Argon2idorscryptwithout forcing password resets?
import hashlib import secrets def hash_password(password): salt = secrets.token_bytes(16) digest = hashlib.sha256(salt + password.encode()).hexdigest() return f"{salt.hex()}:{digest}" def check_password(password, stored): salt_hex, digest = stored.split(":", 1) cand = hashlib.sha256(bytes.fromhex(salt_hex) + password.encode()) return cand.hexdigest() == digest
Show hints (3)
- "SPEED IS THE BUG"
Salts make every user's hash unique, so precomputed tables fail. Yet SHA-256 is built to run fast, letting an attacker test billions of guesses per second on one leaked row.
- "MEMORY HARD KDF"
Use
hashlib.scrypt(orArgon2idwhen a vetted binding is available), store the algorithm and cost parameters (n,r,p) with the 16-byte salt, and compare withhmac.compare_digest. - "REHASH ON LOGIN"
When a user signs in against a legacy SHA-256 row, check the old hash once and immediately overwrite the database row with a fresh
scryptorArgon2idhash.
Show checked explanation
Per-user salts block rainbow tables and identical-password matching, yet SHA-256 runs at billions of guesses per second on GPUs. Switch to a memory-hard password KDF (Argon2id first per OWASP, or stdlib hashlib.scrypt) with a 16-byte secrets.token_bytes salt, stored cost parameters, and hmac.compare_digest. Upgrade legacy rows transparently on successful login.
import hashlib import hmac import secrets def hash_password(pwd, n=16384, r=8, p=5): salt = secrets.token_bytes(16) dk = hashlib.scrypt(pwd.encode(), salt=salt, n=n, r=r, p=p, dklen=32) return f"scrypt${n}${r}${p}${salt.hex()}${dk.hex()}" def check_password(pwd, stored): if not stored.startswith("scrypt$"): return False _, n, r, p, s_hex, d_hex = stored.split("$") dk = hashlib.scrypt(pwd.encode(), salt=bytes.fromhex(s_hex), n=int(n), r=int(r), p=int(p), dklen=32) return hmac.compare_digest(dk, bytes.fromhex(d_hex)) h1, h2 = hash_password("s3cr3t!"), hash_password("s3cr3t!") print("diff_salt:", h1 != h2, "ok:", check_password("s3cr3t!", h1), "bad:", check_password("wrong", h1))
diff_salt: True ok: True bad: False
Author-checked on CPython 3.12.10 with stdlib hashlib.scrypt (N=16384, r=8, p=5), starter SHA-256 hashes, transparent rehash-on-login migration, and maxmem=256 MiB high-N tests; official OWASP, Python hashlib, RFC, and NIST links checked. Checked by an editor other than the author.
Walkthrough
A random 16-byte salt stops precomputed rainbow tables and hides whether two users picked the same password (h1 != h2). It does not slow down guessing against a single leaked row. SHA-256 was designed for high throughput, so a GPU rig can burn through common password dictionaries and mangling rules at roughly 10^10 hashes per second.
Memory-hard key derivation functions (Argon2id and scrypt) force every guess to allocate megabytes of RAM, starving GPU parallelism:
| algorithm | OWASP minimum tier | RAM per hash | Python 3.12 support |
|---|---|---|---|
SHA-256 (salted) | Unsafe for passwords | < 1 KiB | Built in (avoid for passwords) |
Argon2id (RFC 9106) | Preferred (m=19456, t=2, p=1) | 19 MiB (or 46 MiB, t=1) | Via argon2-cffi |
scrypt (RFC 7914) | Recommended (N=16384, r=8, p=5) | 16 MiB (up to 128 MiB, p=1) | Built in (hashlib.scrypt) |
Encode algorithm and cost parameters in the stored string. Storing scrypt$16384$8$5$<salt>$<dk> makes future cost increases painless. On CPython 3.12, hashlib.scrypt defaults to maxmem=32 MiB, which fits N=16384, r=8, p=5 (16 MiB RAM). For N=131072, r=8, p=1 (128 MiB), pass maxmem=256 * 1024 * 1024 explicitly so OpenSSL does not raise ValueError. Always compare derived keys with hmac.compare_digest.
Migrate legacy hashes without forcing resets. Rehash transparently during login once the old digest matches:
def verify_and_upgrade(pwd, stored, save_hash): if stored.startswith("scrypt$"): return check_password(pwd, stored) salt_h, old_h = stored.split(":", 1) cand = hashlib.sha256(bytes.fromhex(salt_h) + pwd.encode()).hexdigest() if not hmac.compare_digest(cand, old_h): return False save_hash(hash_password(pwd)) return True
For dormant accounts that rarely sign in, you can also wrap existing SHA-256 hashes inside scrypt offline so the database holds zero raw SHA-256 rows even before users return.
Common mistakes
- Thinking a random salt makes SHA-256 or SHA-512 safe for passwords. GPUs still brute-force individual leaked hashes at billions of guesses per second.
- Hardcoding
n,r, andpin code without saving them in the hash string. Raising work factors later then breaks every existing login. - Passing
N=131072, r=8to Python'shashlib.scryptwithout raisingmaxmem. CPython's default 32 MiB cap raisesValueErrorin production. - Comparing digests with
==instead ofhmac.compare_digest, or choosingbcryptwithout remembering its 72-byte password truncation limit.
Follow-up questions
- "When should you pick
Argon2idoverhashlib.scryptin Python?" PickArgon2id(for example viaargon2-cffi) for new Python services whenever adding a vetted dependency is fine, because OWASP ranks it first for balanced GPU and side-channel resistance. Use stdlibhashlib.scryptwhen you need zero extra packages or strict stdlib portability. - "What does a server-side pepper add on top of a per-user salt?" A pepper is a secret key kept outside the database (in an HSM or secret manager) and mixed in via HMAC before or after the KDF. If only a SQL backup leaks without the pepper, offline cracking stalls completely.
- "If
scrypttakes 250 ms per login, how do you stop login floods from exhausting server RAM and CPU?" Rate-limit login attempts per account and IP, and cap concurrent KDF workers with a bounded semaphore or queue. Also enforce a sensible maximum password byte length, such as 128 bytes, before hashing.
What a strong answer covers
Explains why salted SHA-256 still falls to offline GPU cracking. Implements memory-hard scrypt (and recommends Argon2id per OWASP) with 16-byte random salts, stored parameters, and hmac.compare_digest, plus zero-reset rehash-on-login migration.
Open in interactive practice deck →