Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 2

Password Storage That Survives a Database Leak

Leak a database on purpose and attack it. Crack an unsalted SHA-256 table with one pass over a wordlist, rebuild the store with Argon2id, test it against wrong, tampered and oversized inputs, measure parameters on your own machine, and migrate legacy rows without a password reset.

Contentsand lesson path

What you will learn

  • Store and verify passwords with an adaptive or memory-hard hashing function and defensible parameters.

01. Goal and setup

Assume the worst has happened: an attacker has a copy of your users table. Good password storage cannot stop the copy, but it decides what the copy is worth. With a fast, unsalted hash, the attacker learns most passwords in seconds and can try them on other sites where the same people reuse them. With a slow, salted, memory-hard hash, every guess costs real time and memory, and has to be repeated for every user.

In this lab you play both sides. You build a weak legacy store and crack it, build an Argon2id store and crack it with the same wordlist, write negative tests for the login check, choose parameters by measuring, and migrate old rows safely.

Some vocabulary first. A password hashing function is a deliberately slow one-way function made for passwords; Argon2id, scrypt, bcrypt and PBKDF2 are the common ones. A salt is a random value stored with each hash, so that the same password gives a different hash for every user. Memory-hard means each computation needs a large block of memory, which makes cheap parallel hardware such as GPUs much less effective for the attacker. Argon2id is the variant of Argon2 recommended by RFC 9106 and the OWASP Password Storage Cheat Sheet.

You need: Python 3.12 and argon2-cffi==25.1.0 (it uses the reference Argon2 C code). Everything runs locally and uses only made-up users and passwords.

Project layout at the end of the lab
password-lab/
├── make_data.py      step 1: fixed users and an attacker wordlist
├── legacy_store.py   step 2: unsalted SHA-256 (the bad example)
├── crack.py          steps 2 and 5: the attacker
├── store.py          step 3: Argon2id hashing and policy
├── build_db.py       step 3: hash every user
├── test_store.py     step 4: positive and negative tests
├── measure.py        step 6: choose parameters by timing
├── migrate.py        step 7: wrap legacy rows
└── login.py          step 7: verify and upgrade on login
Terminal
mkdir password-lab && cd password-lab
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "argon2-cffi==25.1.0"

02. Step 1: create the users and the wordlist

Six users, two of whom share a password, and a 24-word list standing in for the millions of leaked passwords that real attackers use. Two users chose passphrases that are not in the list.

Python · make_data.py
"""Create the lab's fixed users and the attacker's wordlist (no randomness)."""
import json
from pathlib import Path

USERS = {
    "alice": "summer2024",
    "bob": "summer2024",          # same password as alice
    "chen": "letmein",
    "dara": "qwerty123",
    "emre": "violet-anchor-tundra-42",  # long passphrase, not in the wordlist
    "fatima": "Gl4ss-Harbour-Orbit",    # not in the wordlist
}
WORDS = ["123456", "password", "qwerty", "letmein", "welcome", "admin", "iloveyou",
         "monkey", "dragon", "football", "sunshine", "princess", "qwerty123",
         "passw0rd", "summer2023", "summer2024", "winter2024", "abc123", "111111",
         "trustno1", "baseball", "shadow", "master", "hello123"]

Path("users.json").write_text(json.dumps(USERS, indent=1))
Path("wordlist.txt").write_text("\n".join(WORDS) + "\n")
print(f"{len(USERS)} users, {len(WORDS)} words")
Terminal
python make_data.py
Expected output
6 users, 24 words

03. Step 2: build the legacy store and crack it

Python · legacy_store.py
"""How NOT to do it: unsalted SHA-256, as many old systems did."""
import hashlib
import json
from pathlib import Path

users = json.loads(Path("users.json").read_text())
db = {name: hashlib.sha256(pw.encode()).hexdigest() for name, pw in users.items()}
Path("legacy_db.json").write_text(json.dumps(db, indent=1))
print("alice row:", db["alice"][:16] + "...")
print("alice and bob share a hash:", db["alice"] == db["bob"])
Python · crack.py
"""The attacker's view after the leak: try every word against every stored row."""
import hashlib
import json
import sys
import time
from pathlib import Path

from argon2 import PasswordHasher
from argon2.exceptions import VerificationError

db = json.loads(Path(sys.argv[1]).read_text())
words = Path("wordlist.txt").read_text().split()
start, work, cracked = time.perf_counter(), 0, {}

if sys.argv[1] == "legacy_db.json":
    # Unsalted: hash each word ONCE, then look every user up in a table.
    table = {hashlib.sha256(w.encode()).hexdigest(): w for w in words}
    work = len(words)
    cracked = {u: table[h] for u, h in db.items() if h in table}
else:
    # Salted and slow: every guess must be recomputed for every user.
    ph = PasswordHasher()
    for user, stored in db.items():
        for w in words:
            work += 1
            try:
                ph.verify(stored, w)
                cracked[user] = w
                break
            except VerificationError:
                pass

print(f"cracked {len(cracked)} of {len(db)}: {sorted(cracked)}")
print(f"hash computations: {work}")
print(f"seconds: {time.perf_counter() - start:.3f}", file=sys.stderr)
Terminal
python legacy_store.py
python crack.py legacy_db.json 2>/dev/null
Expected output
alice row: 7d0c50df99bb292c...
alice and bob share a hash: True
cracked 4 of 6: ['alice', 'bob', 'chen', 'dara']
hash computations: 24

Two problems show up at once. Alice and Bob have the same stored value, so cracking one cracks both, and anyone reading the table can see who shares a password. Worse, the attacker hashed the wordlist exactly once (24 computations) and then simply looked every user up in a table. Because there is no salt, that table works for every database that used plain SHA-256, and attackers keep large precomputed tables of common passwords. SHA-256 is also designed to be fast: on the machine used for this lab the 24 hashes took well under a millisecond, and GPUs are far faster still. It is a fine hash for files and a poor one for passwords.

04. Step 3: store passwords with Argon2id

The PasswordHasher in store.py uses the minimum configuration in the OWASP cheat sheet: 19 MiB of memory (memory_cost is given in KiB), 2 iterations and 1 lane of parallelism. Treat that as a floor, not a target; step 6 shows how to choose real values. The same file holds the sign-up policy from NIST SP 800-63B-4: at least 15 characters for a password used on its own, permit long passwords (the guideline says at least 64 characters), and check new passwords against a blocklist of breached and common ones instead of imposing composition rules.

If Argon2id is not available, the cheat sheet lists scrypt, bcrypt with a work factor of at least 10 (bcrypt reads only the first 72 bytes of a password), and PBKDF2-HMAC-SHA256 with 600,000 iterations where FIPS 140 validation is required. A fast hash such as SHA-512, even repeated a few thousand times, is not on that list.

Python · store.py
"""Password storage with Argon2id (argon2-cffi), using OWASP's minimum parameters."""
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError

WRAPPED = "sha256+argon2id:"  # prefix for legacy rows wrapped during migration
MAX_LEN = 128  # NIST SP 800-63B-4: permit at least 64 characters; cap to limit abuse
ph = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1)  # m is in KiB


def new_password_problem(password: str, blocklist: set[str]) -> str | None:
    """Sign-up policy for a password used on its own (no second factor)."""
    if len(password) < 15:
        return "too short: use at least 15 characters"
    if len(password) > MAX_LEN:
        return f"too long: at most {MAX_LEN} characters"
    if password.lower() in blocklist:
        return "found in a list of breached or common passwords"
    return None


def hash_password(password: str) -> str:
    return ph.hash(password)  # a fresh random 16-byte salt on every call


def verify_password(stored: str, password: str) -> bool:
    if len(password) > MAX_LEN:
        return False
    try:
        return ph.verify(stored, password)
    except (VerificationError, InvalidHashError):
        return False
Python · build_db.py
"""Store every user with Argon2id and show what a stored value looks like."""
import json
from pathlib import Path

from store import hash_password

users = json.loads(Path("users.json").read_text())
db = {name: hash_password(pw) for name, pw in users.items()}
Path("argon_db.json").write_text(json.dumps(db, indent=1))
_, algorithm, version, params, salt, digest = db["alice"].split("$")
print("alice row:", algorithm, version, params)
print("  salt (base64):", salt)
print("  hash (base64):", digest)
print("alice and bob share a hash:", db["alice"] == db["bob"])
Terminal
python build_db.py
Illustrative output (the salt and hash differ on every run)
alice row: argon2id v=19 m=19456,t=2,p=1
  salt (base64): pADIaMnP4XZj7wyuuGIUYg
  hash (base64): hBEFyDqKO+xqqNnTAS78uxH/LwTuNcmCtoRd3cQDZzQ
alice and bob share a hash: False

The stored value is self-describing. It names the algorithm, the version (v=19 is Argon2 version 1.3) and the parameters, then gives the salt and the hash. That is why verify needs no settings of its own: it reads them from the stored value. It is also what makes later upgrades possible, because old and new rows can sit in the same table and you can tell them apart.

05. Step 4: test the login check, including attacks

A login check fails in two directions. It can reject the right password, which users notice at once, or accept something it should not, which nobody notices until an incident. The tests below cover the second direction on purpose: wrong and empty passwords, another user's password, a 10,000-character input, a stored value that has been edited, and a value that is not a hash at all. The last three tests exercise the sign-up policy.

Python · test_store.py
"""Positive and negative tests. Every line should end in PASS."""
import json
from pathlib import Path

from store import new_password_problem, verify_password

db = json.loads(Path("argon_db.json").read_text())
blocklist = set(Path("wordlist.txt").read_text().split())


def expect(name: str, got: object, want: object) -> None:
    print(f"{'PASS' if got == want else 'FAIL'}  {name}: {got!r}")


GOOD = "violet-anchor-tundra-42"  # emre's real password
expect("right password", verify_password(db["emre"], GOOD), True)
expect("wrong password", verify_password(db["emre"], "violet-anchor-tundra-43"), False)
expect("other user's password", verify_password(db["emre"], "summer2024"), False)
expect("empty password", verify_password(db["emre"], ""), False)
expect("oversized input", verify_password(db["emre"], "x" * 10_000), False)

tampered = db["emre"][:-4] + ("AAAA" if db["emre"][-4:] != "AAAA" else "BBBB")
expect("tampered stored hash", verify_password(tampered, GOOD), False)
expect("garbage stored value", verify_password("not-a-hash", "anything"), False)

expect("short new password", new_password_problem("letmein", blocklist),
       "too short: use at least 15 characters")
breached = {"summer2024summer2024"}
expect("blocklisted new password",
       new_password_problem("Summer2024Summer2024", breached),
       "found in a list of breached or common passwords")
expect("good new password", new_password_problem(GOOD, blocklist), None)
Terminal
python test_store.py
Expected output
PASS  right password: True
PASS  wrong password: False
PASS  other user's password: False
PASS  empty password: False
PASS  oversized input: False
PASS  tampered stored hash: False
PASS  garbage stored value: False
PASS  short new password: 'too short: use at least 15 characters'
PASS  blocklisted new password: 'found in a list of breached or common passwords'
PASS  good new password: None

verify_password turns every library exception into False. argon2-cffi raises VerifyMismatchError for a wrong password and InvalidHashError for a value it cannot parse; a login handler that lets either escape may answer with a 500 error that tells an attacker something different happened. The length cap is checked before any hashing so that huge inputs are refused cheaply.

06. Step 5: leak the new database and attack it again

Terminal
python crack.py argon_db.json
Expected output
cracked 4 of 6: ['alice', 'bob', 'chen', 'dara']
hash computations: 97
Illustrative output (stderr; one desktop machine, your time will differ)
seconds: 2.650

Read this result honestly. The same four users were cracked, because summer2024, letmein and qwerty123 are in the wordlist, and no hashing function can protect a password that the attacker tries early. What changed is the price. The attacker could not build one table for everyone: the salts forced a separate search per user, so the work rose from 24 computations to 97, and each computation now costs tens of milliseconds and 19 MiB of memory instead of a tiny fraction of a millisecond. On the machine used to write this lab, the 97 guesses took about 2.7 seconds; the same arithmetic against a real wordlist of a billion entries is what makes strong passphrases, like Emre's and Fatima's, practically out of reach.

This is the real meaning of "survives a database leak": weak passwords are still lost, strong ones stay safe, and you get time to force resets. The blocklist check from step 3 is what protects the users that hashing cannot.

07. Step 6: choose parameters by measuring

Parameters are a budget. Higher memory and time make each guess costlier for the attacker, but your login server pays the same price for every honest login. Measure on hardware like your production servers, then pick the highest setting that keeps login latency and memory use acceptable at peak load, and add rate limiting so that an attacker cannot use your login endpoint to make you burn CPU. For reference, the defaults of argon2-cffi follow the RFC 9106 low-memory profile: 64 MiB, 3 iterations, 4 lanes.

Python · measure.py
"""Time one hash at a few settings, on YOUR server, to choose parameters."""
import statistics
import time

from argon2 import PasswordHasher

SETTINGS = [(2, 19 * 1024, 1), (1, 46 * 1024, 1), (3, 64 * 1024, 4)]
for t, m, p in SETTINGS:
    ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=p)
    runs = []
    for _ in range(5):
        start = time.perf_counter()
        ph.hash("measure-me-please")
        runs.append(time.perf_counter() - start)
    ms = statistics.median(runs) * 1000
    print(f"t={t} m={m // 1024:>2} MiB p={p}: median {ms:6.1f} ms")
Terminal
python measure.py
Illustrative output (one desktop machine; your numbers will differ)
t=2 m=19 MiB p=1: median   27.7 ms
t=1 m=46 MiB p=1: median   58.5 ms
t=3 m=64 MiB p=4: median   64.2 ms

08. Step 7: migrate legacy rows without a password reset

You still have legacy_db.json, and you do not know anyone's password. Waiting for every user to log in would leave the weak rows exposed for months. Instead, protect them today by hashing the existing SHA-256 value with Argon2id and marking the row as wrapped, which is the second upgrade method in the OWASP cheat sheet. Then, at each successful login, you have the real password for a moment, so replace the wrapped row with a direct Argon2id hash. The same moment is used to upgrade rows whose parameters are older than the current policy, which check_needs_rehash detects.

Wrapping is a transition, not an end state. If the old SHA-256 values also leaked somewhere else, an attacker can match them first and skip the slow layer, a trick called hash shucking. That is why the login path replaces wrapped rows, and why accounts that stay inactive should eventually be expired and asked to reset.

Python · migrate.py
"""Protect legacy rows NOW, without knowing any password: wrap SHA-256 in Argon2id."""
import json
from pathlib import Path

from store import WRAPPED, hash_password

legacy = json.loads(Path("legacy_db.json").read_text())
db = {user: WRAPPED + hash_password(sha_hex) for user, sha_hex in legacy.items()}
Path("migrated_db.json").write_text(json.dumps(db, indent=1))
print("rows wrapped:", sum(v.startswith(WRAPPED) for v in db.values()), "of", len(db))
Python · login.py
"""Log in, and upgrade the stored value whenever the password is in hand."""
import hashlib
import json
from pathlib import Path

from argon2 import PasswordHasher

from store import WRAPPED, hash_password, ph, verify_password


def login(db: dict, user: str, password: str) -> bool:
    stored = db[user]
    if stored.startswith(WRAPPED):
        inner = hashlib.sha256(password.encode()).hexdigest()
        if not verify_password(stored.removeprefix(WRAPPED), inner):
            return False
        db[user] = hash_password(password)  # replace with a direct Argon2id hash
        return True
    if not verify_password(stored, password):
        return False
    if ph.check_needs_rehash(stored):  # parameters older than the current policy
        db[user] = hash_password(password)
    return True


def scheme(value: str) -> str:
    return "wrapped" if value.startswith(WRAPPED) else value.split("$")[3]


if __name__ == "__main__":
    db = json.loads(Path("migrated_db.json").read_text())
    old_policy = PasswordHasher(time_cost=1, memory_cost=8 * 1024, parallelism=1)
    db["zoe"] = old_policy.hash("an-old-but-fine-passphrase")  # hashed years ago
    show = ("alice", "bob", "zoe")
    print("before:", {u: scheme(db[u]) for u in show})
    print("alice wrong password:", login(db, "alice", "summer2023"))
    print("alice right password:", login(db, "alice", "summer2024"))
    print("zoe right password:  ", login(db, "zoe", "an-old-but-fine-passphrase"))
    print("after: ", {u: scheme(db[u]) for u in show})
    print("alice again:", login(db, "alice", "summer2024"))
Terminal
python migrate.py
python login.py
Expected output
rows wrapped: 6 of 6
before: {'alice': 'wrapped', 'bob': 'wrapped', 'zoe': 'm=8192,t=1,p=1'}
alice wrong password: False
alice right password: True
zoe right password:   True
after:  {'alice': 'm=19456,t=2,p=1', 'bob': 'wrapped', 'zoe': 'm=19456,t=2,p=1'}
alice again: True

Alice's wrong password fails against the wrapped row, her right password succeeds and upgrades it, and the next login takes the normal path. Zoe's row, hashed long ago with 8 MiB and one iteration, is upgraded to the current policy the same way. Bob has not logged in, so his row stays wrapped: still protected by Argon2id, waiting for its upgrade.

09. Check your understanding

Practice check · 3 questions

Password storage after a leak

Use what you saw in the lab output.

Q1. Against `argon_db.json`, `crack.py` reported 97 hash computations. If none of the six passwords were in the 24-word list, what would it report?
Q2. The Argon2id hashes leak together with their salts. What do the salts still achieve for the defender?
Q3. Dara's password `qwerty123` was cracked from both databases. Which control would actually have protected her account?
Practice only: not graded, not saved, not evidence.

10. Apply it

Add user accounts to your file-encryption CLI using store.py as a starting point. Extend test_store.py with a test that a row created with weaker parameters is upgraded at the next login, and a test that a wrapped legacy row never accepts the SHA-256 hex string itself as a password. For an extra layer, read the OWASP section on peppering and add a secret pepper, kept outside the database, using HMAC before Argon2id.

11. Review prompt

Without looking back: explain what a salt prevents and what it does not, name the three Argon2id parameters and what each one costs the attacker, and describe in order the two steps of a migration from unsalted SHA-256 that needs no password reset.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check