Cryptographic Hashes, HMAC & Key Derivation
Choose between SHA-256, SHA-3, BLAKE3, HMAC, HKDF, and Argon2id by matching threat model, entropy level, length-extension resistance, and domain separation.
In this lesson (3 bite-sized sections)
Three hash jobs engineers constantly mix up
Cryptographic hash functions look deceptively interchangeable because every one of them takes bytes in and spits fixed-length hex out. In practice, picking the wrong primitive creates subtle breaks. A plain cryptographic hash (SHA-256, SHA-3, BLAKE3) gives collision resistance and integrity over public data, nothing more. A MAC (HMAC-SHA256, KMAC) proves authenticity between parties sharing a secret key. A KDF (HKDF or Argon2id) derives strong cryptographic keys from either high-entropy shared secrets or low-entropy human passwords.
| Primitive family | Input entropy | Secret key? | Designed speed | Primary production job |
|---|---|---|---|---|
| SHA-256 / SHA-3 / BLAKE3 | Any public data | No | Very fast (GB/s) | Content addressing, Merkle trees, file checksums |
| HMAC-SHA256 | Message + secret | Yes | Very fast | Webhooks, API request signing, session MACs |
| HKDF (RFC 5869) | High-entropy IKM | Optional salt | Very fast | Splitting one shared secret into subkeys with domain labels |
| Argon2id / scrypt / bcrypt | Low-entropy password | Per-user salt | Deliberately slow (50-200 ms) | Password verification, passphrase-derived vault keys |
Length-extension attacks and why HMAC exists
SHA-256 and SHA-512 use the Merkle-Damgard construction: they absorb input blocks sequentially and output their final internal compression state directly as the digest. That internal state is all an attacker needs to keep hashing more data. If a naive API authenticates requests with SHA256(secret || message), anyone who sees one valid digest and knows the secret's length can append &role=admin and compute SHA256(secret || message || padding || '&role=admin') without ever knowing secret.
HMAC defeats length extension structurally by wrapping two nested hash passes with XORed key pads: H((K XOR opad) || H((K XOR ipad) || message)). The outer hash seals the inner state so it cannot be continued. Newer sponge and tree hashes like SHA-3 (Keccak) and BLAKE3 are immune to length extension natively, and BLAKE3 adds SIMD tree parallelism that hits 3-10 GB/s on modern CPUs plus built-in keyed MAC and KDF modes.
High-entropy KDFs vs memory-hard password KDFs
Both HKDF and Argon2id are called Key Derivation Functions, yet swapping them is a classic security failure. Use HKDF when your input key material already has full cryptographic entropy, such as an X25519 Diffie-Hellman shared secret or a 256-bit KMS master key. HKDF runs in two fast stages: Extract concentrates uneven entropy (like an elliptic-curve coordinate) into a uniform pseudorandom key using an optional salt, and Expand stretches it into multiple independent keys bound to explicit info context strings (domain separation).
- High-entropy IKMe.g., X25519 shared secret or KMS root key
- HKDF-ExtractPRK = HMAC(salt, IKM) produces uniform 32-byte key
- HKDF-Expand ('enc')info='v1-aes-gcm-key' -> encryption subkey
- HKDF-Expand ('mac')info='v1-hmac-key' -> independent auth subkey
Never feed a user password into HKDF or raw SHA-256. Human passwords have low entropy (often under 40 bits), and GPUs evaluate billions of SHA-256 or HKDF hashes per second. Use a memory-hard password KDF, specifically Argon2id (RFC 9106), configured with a unique 128-bit random salt per user and tuned for tens of MiB of RAM plus 50-100 ms of latency. Requiring large fast memory starves GPU and ASIC cracking rigs far more effectively than CPU iteration loops like PBKDF2 ever could.
Pick the right primitive for each backend requirement.
Sort 4 more items to check
Recap: never build a MAC with SHA256(key || msg) (use HMAC or BLAKE3 keyed mode), never feed passwords into fast hashes or HKDF (use Argon2id with per-user salts), and always separate multi-purpose keys with HKDF info labels.
Sources: RFC 2104, HMAC · RFC 5869, HKDF · BLAKE3 Specification
import hashlib
import hmac
def hkdf_extract(salt: bytes, ikm: bytes) -> bytes:
return hmac.new(salt or b"\x00" * 32, ikm, hashlib.sha256).digest()
def hkdf_expand(prk: bytes, info: bytes, length: int = 32) -> bytes:
okm, prev, counter = b"", b"", 1
while len(okm) < length:
prev = hmac.new(prk, prev + info + bytes([counter]), hashlib.sha256).digest()
okm += prev
counter += 1
return okm[:length]
ikm = hashlib.sha256(b"x25519-shared-secret").digest()
prk = hkdf_extract(b"prod-salt-2026", ikm)
enc_key = hkdf_expand(prk, b"billing-enc-v1")
mac_key = hkdf_expand(prk, b"session-mac-v1")
print("billing-enc-v1 :", enc_key.hex()[:32] + "...")
print("session-mac-v1 :", mac_key.hex()[:32] + "...")
print("keys distinct :", enc_key != mac_key)
payload = b"invoice=4821&amount=9900"
sig = hmac.new(mac_key, payload, hashlib.sha256).digest()
good = hmac.new(mac_key, payload, hashlib.sha256).digest()
bad = hmac.new(mac_key, payload + b"&role=admin", hashlib.sha256).digest()
print("valid verify :", hmac.compare_digest(sig, good))
print("tampered verify:", hmac.compare_digest(sig, bad))
stretched = hashlib.pbkdf2_hmac("sha256", b"user-passphrase", b"u42-salt", 100_000, dklen=32)
print("PBKDF2 (100k) :", stretched.hex()[:32] + "...")Apply
Your turn
The task this lesson builds to.
Specify the hashing and key-derivation layer for an encrypted cloud note-taking app that supports password login, end-to-end encrypted notes derived from a user passphrase, signed share URLs, and deduplicated attachment storage.
Think about
- Which primitive handles low-entropy user passphrases versus high-entropy derived master keys?
- How do you avoid using the exact same derived key for both server login and local note decryption?
- How do you prevent length-extension forgery on signed share URLs?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Evaluate a proposal from a backend team to speed up login latency by replacing Argon2id with HKDF-SHA256 over password + user_salt, and to replace HMAC-SHA256 on internal RPCs with SHA256(secret || body). Explain the exact mathematical and operational impact of each change and propose a safe way to scale login CPU.
Think about
- How many guesses per second can a GPU run against HKDF-SHA256 compared to Argon2id?
- How can an attacker exploit
SHA256(secret || body)on an internal RPC? - How do you handle high login QPS safely without weakening the password KDF?
Draft your design answer here Save your draft, compare against the model answer, and track progress.