14. Key Derivation & Password Hashing
Turning human passwords into strong keys
Humans choose terrible passwords. The string "password123" contains maybe 20 bits of entropy. AES needs a 256-bit key. And when a database is breached, you need the stored passwords to be unrecoverable — an attacker who steals the database shouldn't be able to figure out what anyone's password was. Key derivation functions and password hashing algorithms bridge this gap. They are deliberately designed to be slow.
The Problem with Fast Hashing
Speed is the enemy
SHA-256 can compute billions of hashes per second on modern GPUs. If you store SHA-256(password), an attacker with a leaked database can try billions of password guesses per second. A dictionary of the 10 million most common passwords would be cracked in under a second. This is why we need something deliberately slow.
Cryptographic hash functions like SHA-256 are designed to be fast. That's a feature when you're verifying file integrity or building Merkle trees. It's a catastrophe when you're storing passwords. An attacker with a GPU farm can hash every word in every dictionary, every common substitution (p@ssw0rd), and every short random string in hours. We need hash functions where each guess costs real time and real resources.
Salt: Preventing Precomputation
Without salt, the same password always produces the same hash. An attacker can precompute a massive "rainbow table" — a lookup table mapping hashes back to passwords — and crack any database instantly by looking up each hash.
The fix: generate a random salt (typically 16–32 bytes) unique
to each user, and compute hash(salt || password). Store the salt alongside
the hash. Now the same password with different salts produces completely different
hashes, and rainbow tables become useless.
Same password, different salts
User: alice
Salt: 9f2a1b3c... (random 16 bytes)
Password: hunter2
Hash: hash("9f2a1b3c..." || "hunter2") = 4a7d91e3...
User: bob
Salt: 7e5d8f01... (different random 16 bytes)
Password: hunter2
Hash: hash("7e5d8f01..." || "hunter2") = c38bf20a...
Same password, completely different hashes.
Without Salt
Same password → same hash, every time.
Attacker precomputes a rainbow table once, cracks all databases forever.
If two users share a password, the attacker sees identical hashes.
With Salt
Same password + different salt → different hash.
Rainbow tables are useless — the attacker would need a separate table for every possible salt.
Identical passwords are invisible in the database.
Key Stretching: Making It Slow
Salt stops precomputation, but an attacker can still brute-force individual passwords if the hash is fast. Key stretching solves this by running the hash function thousands or millions of times in a loop. Each guess now takes milliseconds instead of nanoseconds.
The math of key stretching
Without stretching:
SHA-256: ~1 nanosecond per hash
10,000,000 common passwords × 1 ns = 0.01 seconds
With 100,000 iterations:
~0.1 seconds per guess
10,000,000 passwords × 0.1 s = 11.6 days
The defender computes the hash once (at login).
The attacker must compute it for every guess.
The idea is beautifully asymmetric: the legitimate server verifies one password per login attempt and can afford to spend 100–500 milliseconds. The attacker needs to verify millions or billions of guesses, and that same delay becomes crippling.
bcrypt
Designed in 1999 by Niels Provos and David Mazières, bcrypt is based on the Blowfish cipher's expensive key setup phase. It was one of the first password hashing functions built to be deliberately slow, and it remains widely used today.
Anatomy of a bcrypt hash
$2b$12$WApznUPhDubN0oeveSXHp.Nh8F9MkqU2VKFJaoYPOLdaQoQ3Sluq
││ ││ │ │
││ ││ └── 22-char salt ──────┘└── 31-char hash
││ └┘
││ 12 = cost factor (2^12 = 4096 iterations)
└┘
2b = bcrypt version
Key properties of bcrypt:
- Cost factor: a single number that controls iterations exponentially. Cost 10 ≈ 100ms, cost 12 ≈ 300ms, cost 14 ≈ 1 second.
- Built-in salt: the salt is embedded in the output string, so you never forget to use one.
- 72-byte limit: passwords longer than 72 bytes are silently truncated. This is bcrypt's most notable limitation.
- Proven track record: 25+ years of deployment with no practical breaks.
scrypt
Designed by Colin Percival in 2009, scrypt introduced a crucial new idea: memory hardness. bcrypt and PBKDF2 are CPU-hard — they need many iterations — but an attacker with GPUs or custom ASICs can run many instances in parallel cheaply. scrypt requires a large block of RAM for each hash computation, and memory is much harder to parallelize than computation.
scrypt parameters
scrypt(password, salt, N, r, p, keyLength)
N = CPU/memory cost parameter (must be power of 2)
N = 2^14 (16384) for interactive logins
N = 2^20 (1048576) for sensitive keys
r = block size (controls memory per block, typically 8)
Memory used ≈ 128 × N × r bytes
p = parallelism (number of independent chains, typically 1)
Example: N=2^14, r=8, p=1 → ~16 MB of RAM per hash
scrypt is used by the Tarsnap backup service and was adopted by several cryptocurrencies (Litecoin, Dogecoin) for proof-of-work mining specifically because memory-hard functions resist ASIC optimization.
Argon2: The Modern Standard
Argon2 won the Password Hashing Competition in 2015, a multi-year open competition modeled after the AES and SHA-3 competitions. It was designed to address the limitations of every previous algorithm while providing clear, tunable parameters.
Argon2 comes in three variants:
- Argon2d — Data-dependent memory access. Maximizes GPU/ASIC resistance but vulnerable to side-channel attacks (timing leaks).
- Argon2i — Data-independent memory access. Resistant to side-channel attacks but slightly less GPU-resistant.
- Argon2id — Hybrid. First pass is data-independent (Argon2i), subsequent passes are data-dependent (Argon2d). Gets the best of both worlds.
Use Argon2id
Argon2id is the recommended choice for virtually all new applications. It provides both side-channel resistance (from the Argon2i first pass) and GPU/ASIC resistance (from the Argon2d subsequent passes). Unless you have a very specific threat model, Argon2id is the right answer.
Argon2id parameters
argon2id(password, salt, timeCost, memoryCost, parallelism)
timeCost = number of iterations (passes over memory)
memoryCost = memory in KB (e.g., 65536 = 64 MB)
parallelism = number of threads
Recommended for login:
timeCost=3, memoryCost=65536 (64 MB), parallelism=4
Target: ~200ms on server hardware
Output example:
$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHQ$hash...
│ │ │ │ │
variant ver parameters base64 salt base64 hash
HKDF: Deriving Multiple Keys
HKDF solves a different problem entirely. You already have a strong secret — perhaps the shared secret from an ECDHE key exchange — and you need to derive multiple independent keys from it (one for encryption, one for MAC, one for each direction of communication). HKDF is fast, not slow, because the input is already high-entropy.
HKDF two-step process
Step 1: Extract — concentrate entropy into a fixed-size key
PRK = HMAC-Hash(salt, input_key_material)
Step 2: Expand — derive as many keys as needed
T(1) = HMAC-Hash(PRK, info || 0x01)
T(2) = HMAC-Hash(PRK, T(1) || info || 0x02)
T(3) = HMAC-Hash(PRK, T(2) || info || 0x03)
...
output = T(1) || T(2) || T(3) || ... (truncated to desired length)
The "info" parameter lets you derive different keys for different purposes:
encryption_key = HKDF(shared_secret, salt, "encryption")
mac_key = HKDF(shared_secret, salt, "authentication")
HKDF is used in TLS 1.3 (deriving traffic keys from the handshake secret), the Signal protocol (ratcheting keys forward), and WireGuard (deriving transport keys). It is not a password hashing function — never use it to hash passwords directly.
PBKDF2
PBKDF2 (Password-Based Key Derivation Function 2) is the oldest widely-deployed password hashing standard, defined in RFC 2898. Its design is simple: iterate HMAC with the password and salt for a specified number of rounds.
PBKDF2 internals
PBKDF2(password, salt, iterations, hashFunction, outputLength)
U1 = HMAC-SHA256(password, salt || INT(1))
U2 = HMAC-SHA256(password, U1)
U3 = HMAC-SHA256(password, U2)
...
output = U1 XOR U2 XOR U3 XOR ... XOR U(iterations)
Example: WPA2 Wi-Fi uses PBKDF2 with:
Hash: HMAC-SHA1
Iterations: 4096
Output: 256 bits (the pairwise master key)
PBKDF2 is still found everywhere — WPA2 Wi-Fi, the iOS keychain, .NET's password hashing — but it has a fundamental weakness: it is not memory-hard. An attacker with GPUs can run millions of PBKDF2 instances in parallel because each one needs only a few bytes of state. For new systems, Argon2id is preferred.
Choosing Parameters
The right parameters depend on your use case and your hardware. The goal is always the same: make each hash take long enough that brute-force attacks become impractical, but not so long that legitimate users notice.
Parameter guidelines
| Use case | Algorithm | Memory | Iterations | Target time |
|---|---|---|---|---|
| Interactive login | Argon2id | 64 MB | 3 | ~200ms |
| Background authentication | Argon2id | 128 MB | 3 | ~500ms |
| File/disk encryption key | Argon2id | 256 MB | 4+ | 1–3 seconds |
| Legacy system | bcrypt | N/A | cost 12+ | ~300ms |
The key principle: choose parameters that make the operation take 100–500ms on your hardware for login use cases. For key derivation from a password (encrypting a file, deriving a wallet key), you can afford seconds. As hardware gets faster, increase your parameters. bcrypt's cost factor has risen from 10 to 12–14 over the years; Argon2's recommended memory has grown from 32 MB to 64 MB and beyond.
What Happens in a Breach
-
The database leaks
An attacker gets usernames, salts, and hashed passwords. This has happened to LinkedIn, Adobe, Yahoo, and hundreds of other companies.
-
The attacker starts guessing
They take a dictionary of common passwords and compute the hash for each one using the stolen salt.
-
SHA-256: minutes to crack everything
At billions of hashes per second on a GPU cluster, the attacker tears through every common password and most short passwords in minutes. The entire database is compromised.
-
bcrypt (cost 12): years per password
At ~300ms per guess, the attacker can try only ~3 guesses per second per core. Ten million guesses would take over a month per user. Most passwords survive.
-
Argon2id (64 MB): GPU attacks become impractical
Each guess needs 64 MB of memory. A GPU with 8 GB of VRAM can run only ~125 parallel instances instead of thousands. The memory bottleneck destroys the attacker's advantage.
Time to crack 10 million common passwords
SHA-256: |█ < 1 second
PBKDF2 (100k iter): |████████████ ~12 days
bcrypt (cost 12): |███████████████████████ ~38 days
Argon2id (64 MB): |██████████████████████████████████████ months+
(GPU-based attack, approximate — actual times depend on hardware)
Real-World Usage
| Algorithm | Where it's used |
|---|---|
| bcrypt | Ruby on Rails, PHP (password_hash), many web applications |
| Argon2 | Newer applications, libsodium, 1Password, Bitwarden |
| PBKDF2 | WPA2 Wi-Fi, iOS keychain, .NET, LUKS (older versions) |
| scrypt | Tarsnap, Litecoin/Dogecoin, some key derivation |
| HKDF | TLS 1.3, Signal protocol, WireGuard |
Try It Yourself — Why Salt Matters
Enter a password and see how salting prevents identical passwords from producing identical hashes. Without salt, an attacker instantly spots shared passwords in a leaked database.
Brute Force Cost Calculator
How long would it take to brute-force a password database? Adjust the algorithm, GPU count, and dictionary size to see the difference between fast hashes and purpose-built password hashing.
Hash Format Decoder
Password hashes embed their parameters in the output string. Select a format to see each component decoded.
Key Takeaways
- Never store passwords with a fast hash like SHA-256 — use a purpose-built password hashing function
- Always use a unique random salt per user to prevent rainbow table attacks
- Key stretching makes each guess expensive: the defender pays once, the attacker pays billions of times
- Argon2id is the modern standard — it is memory-hard, GPU-resistant, and side-channel resistant
- bcrypt remains a solid choice where Argon2 is unavailable; PBKDF2 is acceptable but not memory-hard
- HKDF is for deriving keys from existing secrets, not for password hashing
- Tune parameters so hashing takes 100–500ms on your hardware, and increase them over time
Password hashing is one of the few areas in cryptography where being slow is a feature. Every other primitive we've studied — AES, SHA-256, ECDH — aims for speed. But when the input is a human-chosen password, speed is the enemy. The right KDF turns a weak password into an expensive-to-guess credential and a strong secret into as many independent keys as you need. Choose Argon2id for passwords, HKDF for key derivation, and always measure your parameters against real hardware.