Sub topic 15
Storing Passwords: Salts and Slow Hashes
This chapter assumes you have read the earlier chapters on cryptographic hash properties, SHA-256 for integrity, and HMAC. You should be comfortable with Python bytes, hex encoding, and the idea that a hash is one-way but fast to compute.
The threat model
A login system must check a password without keeping the password. The usual approach is to store a hash and compare it at login. The risk to plan for is a database leak. After a leak, the attacker has every stored hash and can try guesses offline, as fast as their hardware allows, with no rate limit and no lockout.
Preimage resistance does not protect you here. Users pick passwords from a small, predictable set, so the attacker never needs to invert the function. They hash candidate passwords and look for a match. The defense is to make each guess expensive and to stop the attacker from reusing work across accounts.
Why a plain fast hash fails
SHA-256 is designed to be fast. A single modern GPU can compute billions of SHA-256 hashes per second. A password stored as sha256(password) has two problems:
- Guessing is cheap, so even a large wordlist is exhausted in minutes.
- Identical passwords produce identical hashes. The attacker can precompute a table of common passwords once (or download one) and look up every leaked hash in it.
import hashlib
# Attacker's precomputed table: hash -> password
common = ["123456", "password", "letmein", "qwerty"]
table = {hashlib.sha256(p.encode()).hexdigest(): p for p in common}
leaked = hashlib.sha256(b"letmein").hexdigest()
print(table.get(leaked)) # letmeinOne table cracks every account that uses a listed password, and a lookup costs almost nothing.
Salts
A salt is a random value, generated per password, stored next to the hash, and mixed into the hash input. It is not secret. Its job is to make the hash of each password unique.
With a unique salt per user:
- Two users with the same password get different stored hashes.
- A precomputed table is useless, because the attacker would need one table per salt.
- The attacker must attack each account separately, so the cost of cracking N accounts grows N-fold.
A salt does not make a single guess slower. Against one weak password, a salted fast hash still falls quickly. That is why you also need a slow function.
Use at least 16 random bytes from a cryptographic source such as os.urandom or the secrets module. Do not use random, a username, or a timestamp. A reused or predictable salt brings back the shared-table problem.
Deliberately slow, memory-hard hashes
A password hashing function has a tunable cost. You set it so one verification takes a noticeable but acceptable time on your server, such as 50 to 250 milliseconds. A legitimate user pays that once per login. An attacker pays it for every guess.
Cost can be time, memory, or both:
| Function | Cost lever | Notes |
|---|---|---|
| PBKDF2-HMAC-SHA256 | Iteration count | Time only. Cheap to run on GPUs. Common where FIPS compliance matters. |
| bcrypt | Work factor (log2 of rounds) | Small fixed memory. Truncates passwords at 72 bytes. |
| scrypt | N, r, p | Memory-hard. In the Python standard library. |
| Argon2id | Time, memory, parallelism | Current general recommendation. Needs a third-party package in Python. |
Memory-hard means each guess needs a large block of RAM, not only CPU cycles. GPUs and custom chips have thousands of cores but little memory per core, so requiring, say, 16 MiB per guess removes much of their advantage.
A worked example with scrypt
The standard library function hashlib.scrypt takes a password, a salt, and the cost parameters n (CPU and memory cost, a power of two), r (block size), and p (parallelism). Memory use is roughly 128 * n * r bytes. With n=2**14 and r=8, that is 16 MiB.
import hashlib
import hmac
import os
def hash_password(password: bytes):
salt = os.urandom(16)
derived = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1)
return salt, derived
def verify_password(password: bytes, salt: bytes, derived: bytes) -> bool:
candidate = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1)
return hmac.compare_digest(candidate, derived)
salt, stored = hash_password(b"correct horse")
print(verify_password(b"correct horse", salt, stored))
print(verify_password(b"wrong guess", salt, stored))hmac.compare_digest compares in constant time, so response timing does not reveal how many leading bytes matched. The first call prints True and the second prints False.
Measuring cost
Pick parameters by measuring on your own hardware, not by copying numbers. This script times scrypt at three memory settings. Python's default memory limit for scrypt is about 32 MiB, so larger settings need an explicit maxmem.
import hashlib
import os
import time
salt = os.urandom(16)
for log_n in (12, 14, 16):
start = time.perf_counter()
hashlib.scrypt(b"benchmark", salt=salt, n=2**log_n, r=8, p=1,
maxmem=2**27)
elapsed = (time.perf_counter() - start) * 1000
print(f"n=2^{log_n}: {elapsed:.0f} ms")Each step up in log_n doubles both the time and the memory. Choose the largest setting your login path can afford under peak load. Remember that many simultaneous logins each need their own memory block.
Storing parameters with the hash
Costs rise as hardware improves, so you will change parameters later. Store the algorithm, the parameters, the salt, and the derived key together in one string. Then old and new records can coexist, and you can upgrade an account at its next successful login.
import hashlib
import hmac
import os
def encode(password: bytes, n=2**14, r=8, p=1) -> str:
salt = os.urandom(16)
key = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p)
return f"scrypt${n}${r}${p}${salt.hex()}${key.hex()}"
def check(password: bytes, record: str) -> bool:
_, n, r, p, salt_hex, key_hex = record.split("$")
key = hashlib.scrypt(password, salt=bytes.fromhex(salt_hex),
n=int(n), r=int(r), p=int(p))
return hmac.compare_digest(key, bytes.fromhex(key_hex))
record = encode(b"correct horse")
print(record[:40] + "...")
print(check(b"correct horse", record))
print(check(b"Correct horse", record))Edge cases and common mistakes
- Fast hash with a salt.
sha256(salt + password)stops table reuse but leaves guessing cheap. Salting alone is not enough. - Home-made stretching. Looping SHA-256 yourself is worse than PBKDF2, which is itself weaker than scrypt or Argon2id. Use a vetted function.
- bcrypt length limit. bcrypt ignores bytes beyond 72. Pre-hashing long passwords is a known workaround, but it must be done carefully, for example by encoding the digest so it contains no zero bytes.
- Unicode. Normalize passwords (for example to NFKC) and encode as UTF-8 before hashing, or the same visible password may fail on another device.
- Denial of service. A slow hash is also a cost to you. Rate-limit login attempts and cap password length (such as 1024 bytes) so an attacker cannot force huge inputs through an expensive function.
- Pepper. A pepper is a secret key kept outside the database, such as in a key management service. You can apply it with HMAC before or after hashing. It helps if only the database leaks, but it adds key management work. Treat it as an extra layer, not a replacement for salts and slow hashing.
- Comparison. Always use a constant-time comparison for derived keys.
Summary of roles
A salt defeats shared precomputation and forces per-account work. A slow, memory-hard function raises the price of every guess. Stored parameters let you raise that price over time. Constant-time comparison closes a timing leak. None of these can rescue a very weak password, so combine them with length requirements and checks against known breached passwords.
Exercise
A site stores sha256(salt + password) with a unique 16-byte random salt per user, and the database leaks. Name one attack the salt prevents and one it does not, and say what change fixes the second problem.
Show answer
The salt prevents precomputed lookup tables and the cracking of many accounts with one table, since two users with the same password get different hashes. It does not slow down guessing against a single account, because SHA-256 is still fast and a GPU can test billions of candidates per second. Replace the hash with a deliberately slow, memory-hard function such as scrypt or Argon2id, keep the per-user salt, and store the cost parameters with each record.