"""how-password-hashing-works-bcrypt-scrypt-argon2.py: what slow password hashing costs the server that runs it. Two parts: 1. Cost, from a measurement. Reads the hashing bench CSV (datasets/password-hash-bench.csv, written by code/password-hash-bench.py: median time per hash on ONE CPU thread, and peak memory per hash for the memory-hard functions) and prints, for each password-hashing setting: the time one login takes, the CPU time 1,000 logins take, the CPU threads needed to keep up with 100 logins a second, and how many logins fit in 1 GiB of memory at once. It also prints how much each bcrypt cost step multiplied the measured time. These are costs to the defender on one ordinary CPU thread, not an attacker's rate on special hardware. 2. bcrypt's 72-byte limit, run live with the installed bcrypt package. bcrypt reads at most 72 bytes of a password. Version 5.0.0 refuses longer input with a ValueError that suggests truncating by hand; older versions truncated silently. Either way, two passwords that share their first 72 bytes end up with the same hash. The demo uses a fixed salt so its output is the same on every run, and it prints how many characters fit in 72 bytes of UTF-8 for a few scripts. Run: python how-password-hashing-works-bcrypt-scrypt-argon2.py --bench password-hash-bench.csv Needs: Python 3.10+, and the bcrypt package (pip install bcrypt) for part 2; part 1 is standard library only. """ import argparse import csv import math GIB_MIB = 1024 DEMO_SALT = b"$2b$10$passwordpasswordcomde." # a fixed (not random) salt, only so the demo prints the same hashes every run SETTINGS = [ # (family, setting) rows of the bench that are password-hashing settings, in display order ("Argon2id", "m=19456 KiB t=2 p=1"), ("Argon2id", "m=47104 KiB t=1 p=1"), ("Argon2id", "m=7168 KiB t=5 p=1"), ("scrypt", "N=2^17 r=8 p=1"), ("scrypt", "N=2^13 r=8 p=10"), ("bcrypt", "cost 10"), ("bcrypt", "cost 11"), ("bcrypt", "cost 12"), ("bcrypt", "cost 13"), ("PBKDF2-HMAC-SHA256", "600,000 iterations"), ] def load(path): rows = list(csv.DictReader(open(path, newline="", encoding="utf-8"))) return {(r["family"], r["setting"]): r for r in rows} def cost_rows(bench): out = [] for key in SETTINGS: r = bench[key] ms = float(r["median_ms"]) mem = float(r["peak_mem_mib"]) if r["peak_mem_mib"] else None out.append({ "family": key[0], "setting": key[1], "owasp": r["owasp"] or "-", "ms": ms, "cpu_s_per_1000": ms, # 1,000 logins x ms per login / 1,000 ms per second "threads_for_100_per_s": math.ceil(100 * ms / 1000), "mem_mib": mem, "concurrent_per_gib": math.floor(GIB_MIB / mem) if mem else None, }) return out def bcrypt_steps(bench): t = [float(bench[("bcrypt", f"cost {c}")]["median_ms"]) for c in (10, 11, 12, 13)] fastest11 = float(bench[("bcrypt", "cost 11")]["min_ms"]) return [(c, t[i + 1] / t[i]) for i, c in enumerate((11, 12, 13))], t[3] / t[0], fastest11 def print_costs(bench): print("Cost, measured on one CPU thread (median of the bench runs)") print(f"{'function':20s} {'setting':22s} {'OWASP':18s} {'ms/login':>9s} {'CPU s/1000':>10s} {'threads@100/s':>13s} {'MiB':>6s} {'per GiB':>7s}") for r in cost_rows(bench): mem = f"{r['mem_mib']:.1f}" if r["mem_mib"] else "-" per = str(r["concurrent_per_gib"]) if r["concurrent_per_gib"] else "-" print(f"{r['family']:20s} {r['setting']:22s} {r['owasp']:18s} {r['ms']:9.1f} {r['cpu_s_per_1000']:10.1f} " f"{r['threads_for_100_per_s']:13d} {mem:>6s} {per:>7s}") steps, total, fastest11 = bcrypt_steps(bench) print("bcrypt: each cost step should double the work. Measured median ratios: " + ", ".join(f"cost {c - 1}->{c} x{x:.2f}" for c, x in steps) + f"; cost 10->13 x{total:.2f} (theory x8). Fastest cost-11 run: {fastest11:.1f} ms.") meta = next(iter(bench.values())) print(f"bench: {meta['cpu']}, measured {meta['generated_at']}") def utf8_budget(): samples = [("ASCII letter", "a"), ("accented Latin", "é"), ("Cyrillic", "Ж"), ("Chinese", "中"), ("emoji", "\U0001F600")] return [(label, len(ch.encode("utf-8")), 72 // len(ch.encode("utf-8"))) for label, ch in samples] def demo_72(): import bcrypt print(f"\nbcrypt's 72-byte limit, live (bcrypt {bcrypt.__version__})") head = b"correct horse battery staple, " * 3 head = head[:72] one, two = head + b" -- ending one", head + b" -- ending two" print(f"two passwords: {len(one)} and {len(two)} bytes, identical in the first 72 bytes, different after") try: bcrypt.hashpw(one, DEMO_SALT) refused = None except ValueError as e: refused = str(e) if refused: print(f"hashpw(73+ bytes) -> ValueError: {refused}") h1, h2 = bcrypt.hashpw(one[:72], DEMO_SALT), bcrypt.hashpw(two[:72], DEMO_SALT) print("after truncating by hand, as the message suggests:") else: h1, h2 = bcrypt.hashpw(one, DEMO_SALT), bcrypt.hashpw(two, DEMO_SALT) print("this bcrypt version accepted the long input (it truncates silently):") print(f" hash of password one: {h1.decode()}") print(f" hash of password two: {h2.decode()}") print(f" identical: {h1 == h2}; checkpw(password two, hash one) -> {bcrypt.checkpw(two[:72] if refused else two, h1)}") print("characters that fit in 72 bytes of UTF-8:") for label, b, n in utf8_budget(): print(f" {label:15s} {b} byte(s) each -> {n}") def main(): ap = argparse.ArgumentParser(description="What slow password hashing costs the server (from the bench CSV), and bcrypt's 72-byte limit.") ap.add_argument("--bench", required=True, help="password-hash-bench.csv") ap.add_argument("--no-bcrypt", action="store_true", help="skip the live bcrypt demo") a = ap.parse_args() print_costs(load(a.bench)) if not a.no_bcrypt: demo_72() if __name__ == "__main__": main()