Show contents
Chapter 1 of 7 · 20 min
Storing passwords
By the end of this chapter, you'll be able to
- Explain why a password must never be stored in plain text
- Tell encryption from hashing
- Hash a password with a salt and a slow function
- Verify a password without leaking information
Encrypt or hash?
Two operations are often confused:
- encrypting means making a message unreadable with a key, in a reversible way: whoever has the key can decrypt;
- hashing means computing a fixed-size digest, in an irreversible way: the original text cannot be recovered from the digest.
For passwords, we hash. The server does not need to know your password: it only needs to check that the digest of what you type equals the stored digest.
import hashlib
for word in ["sunshine2026", "sunshine2027", "sunshine2026"]:
print(word, hashlib.sha256(word.encode()).hexdigest()[:16])
sunshine2026 5d6180aa498ee733
sunshine2027 dc4752b0e4651047
sunshine2026 5d6180aa498ee733
SHA-256 is a hash function: a single different character changes the whole digest (only its first 16 hexadecimal characters are shown here), and the same text always gives the same digest.
Two problems: speed and duplicates
SHA-256 was designed to be fast. That is a strength for checking a file, a weakness for a password: an attacker who has stolen the digests can try billions of passwords per second with a graphics card. And since the same password gives the same digest, they spot at a glance every account sharing a common password.
The two remedies:
- a salt: a random value, different for each account, added to the password before hashing, and stored next to the digest. Two accounts with the same password then get different digests;
- a deliberately slow function, which repeats the computation thousands of times: unnoticeable for a login, ruinous for an attacker who must test billions of passwords.
PBKDF2, written in a few lines
PBKDF2 is a standard key derivation function that applies both ideas: it repeats an HMAC (a digest computed with a key, here the password) a large number of times, mixing the results. In Python, hashlib.pbkdf2_hmac provides it; it does not exist in your browser's Python, so let's write it ourselves, to see what it does:
import hmac
def pbkdf2(password, salt, iterations):
"""PBKDF2-HMAC-SHA256, a single 32-byte block."""
u = hmac.new(password, salt + b"\x00\x00\x00\x01", "sha256").digest()
result = int.from_bytes(u, "big")
for _ in range(iterations - 1):
u = hmac.new(password, u, "sha256").digest()
result ^= int.from_bytes(u, "big")
return result.to_bytes(32, "big")
salt_awa, salt_kofi = bytes.fromhex("8f3a91c2d45e6b70"), bytes.fromhex("1b7c0e9fa2d34856")
print("Awa: ", pbkdf2(b"sunshine2026", salt_awa, 10_000).hex()[:16])
print("Kofi:", pbkdf2(b"sunshine2026", salt_kofi, 10_000).hex()[:16])
Awa: 5c1d53eda21080d0
Kofi: 211ad0ca43967e03
Same password, different salts: the digests have nothing in common any more. In real life, the salt is drawn at random with secrets.token_bytes(16); here it is fixed so that the example always gives the same result. The number of iterations is reduced so that the example is instant: OWASP (a reference foundation for web security) recommends at least 600,000 iterations for PBKDF2-HMAC-SHA256.
At login, the server redoes the computation with the stored salt and compares the digests.
Text description of the animation
- The password arrives over an encrypted connection (HTTPS). It will never be written to disk.
- A random salt, specific to this account.
- The computation is deliberately expensive: a fraction of a second for you, centuries to test every password.
- We store the salt and the digest. A database leak does not reveal the passwords.
- At login, the server redoes the computation with the stored salt and compares the digests.
Verifying a password
import hmac
def pbkdf2(password, salt, iterations):
u = hmac.new(password, salt + b"\x00\x00\x00\x01", "sha256").digest()
result = int.from_bytes(u, "big")
for _ in range(iterations - 1):
u = hmac.new(password, u, "sha256").digest()
result ^= int.from_bytes(u, "big")
return result.to_bytes(32, "big")
ITERATIONS = 10_000
salt = bytes.fromhex("8f3a91c2d45e6b70")
stored = pbkdf2(b"sunshine2026", salt, ITERATIONS)
def verify(attempt):
return hmac.compare_digest(pbkdf2(attempt.encode(), salt, ITERATIONS), stored)
print(verify("sunshine2026"), verify("Sunshine2026"))
True False
hmac.compare_digest compares two values in a time that does not depend on where they differ. An ordinary == comparison stops at the first different byte: by measuring the response time very precisely, an attacker could deduce information from it. This is called a timing attack.
For a real application, use a proven library rather than your own code: Argon2id (for example with the Python package argon2-cffi) is today the first recommended choice; bcrypt and scrypt remain acceptable. Writing PBKDF2 yourself is for understanding, not for replacing these libraries.
Mini-lab: the cost of iterationsPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: store then verify
Write a function store(password, salt) that returns the string "pbkdf2$ITERATIONS$SALT$DIGEST" (salt and digest in hexadecimal), and a function verify(attempt, stored) that reads this string back and checks the attempt. This format, which keeps the parameters with the digest, lets you raise the number of iterations later without breaking older accounts.
Hint 1
text.split("$") cuts the stored string into its four pieces.Hint 2
bytes.fromhex converts the salt back; compare the digests with hmac.compare_digest.Show the solution and common mistakes
import hmac
def pbkdf2(password, salt, iterations):
u = hmac.new(password, salt + b"\x00\x00\x00\x01", "sha256").digest()
result = int.from_bytes(u, "big")
for _ in range(iterations - 1):
u = hmac.new(password, u, "sha256").digest()
result ^= int.from_bytes(u, "big")
return result.to_bytes(32, "big")
def store(password, salt, iterations=10_000):
digest = pbkdf2(password.encode(), salt, iterations)
return f"pbkdf2${iterations}${salt.hex()}${digest.hex()}"
def verify(attempt, stored):
_, iterations, salt, digest = stored.split("$")
computed = pbkdf2(attempt.encode(), bytes.fromhex(salt), int(iterations))
return hmac.compare_digest(computed.hex(), digest)
stored = store("baobab-42", bytes.fromhex("5ac2e07d913f4b68"))
print(stored[:40] + "…")
print(verify("baobab-42", stored), verify("baobab-43", stored))
pbkdf2$10000$5ac2e07d913f4b68$9491fc5076…
True False
Common mistakes:
- Reusing the same salt for every account: two identical passwords give identical digests again, and the salt loses its point.
- Comparing with
==: the result is right, but the duration of the comparison can inform an attacker.
Summary
- 1A password is hashed, not encrypted, and never stored in plain text.
- 2A random salt per account makes precomputed tables useless.
- 3A deliberately slow function (Argon2id, bcrypt, scrypt, PBKDF2) slows down brute-force attacks.
- 4Verification recomputes the digest with the stored salt, compared with hmac.compare_digest.
- 5In production, use a proven library rather than your own code.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.