TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › KDFs versus Password Hashes, and Peppers

KDFs versus Password Hashes, and Peppers

"Key derivation function" names two different tools that are often confused. One kind turns a strong secret (a Diffie–Hellman output, a master key) into several independent keys, and it should be fast: HKDF. The other kind turns a weak secret (a password) into a key or a stored verifier, and it must be slow: Argon2id, scrypt, PBKDF2. Using the fast kind on passwords, or the slow kind where it isn't needed, are both real mistakes. This lesson also covers peppers, a second secret that protects password hashes even when the whole database is stolen.

Two jobs, two tools

KDF for high-entropy input Password-based KDF / password hash
input a DH shared secret, a master key, a random 256-bit value a password or passphrase
goal uniform, independent keys for each purpose make every guess expensive
speed fast (microseconds) deliberately slow (tens to hundreds of milliseconds), memory-hard
examples HKDF (RFC 5869), the TLS 1.3 key schedule, KMAC, NIST SP 800-108 KDFs Argon2id, scrypt, bcrypt, PBKDF2
salt optional (a fixed or protocol salt is fine) mandatory, random per password
typical use session keys, per-purpose subkeys, key rotation password storage, encrypting a file with a passphrase

The rule of thumb: if a human chose or remembers the secret, it needs a password-based KDF. If a machine generated it with 128+ bits of entropy, HKDF is enough, and slowing it down buys nothing.

HKDF for subkeys

One master key, three purposes. The info label (domain separation) makes each derived key independent: learning the token-signing key reveals nothing about the file-encryption key.

python · try it yourself
import hmac, hashlib
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF, HKDFExpand

# RFC 5869 test case 1
okm = HKDF(algorithm=hashes.SHA256(), length=42, salt=bytes(range(13)), info=bytes(range(0xf0, 0xfa))).derive(b"\x0b" * 22)
print("RFC 5869 case 1 OK:", okm.hex().startswith("3cb25f25faacd57a90434f64d0362f2a"))

# One master key, several independent subkeys by `info` (domain separation)
master = bytes.fromhex("aa" * 32)                  # fixed lab key; real: from a KMS or os.urandom(32)
for purpose in (b"files/encrypt v1", b"files/mac v1", b"tokens/sign v1"):
    k = HKDFExpand(algorithm=hashes.SHA256(), length=32, info=purpose).derive(master)
    print(f"{purpose.decode():18} {k.hex()[:24]}...")

# Pepper: HMAC the password hash with a key that lives outside the database
pepper = bytes.fromhex("5e" * 32)                  # lab value; real: in a vault/HSM, never in the DB
stored_hash = bytes.fromhex("9f" * 32)             # stands in for an Argon2id output
print("peppered:", hmac.new(pepper, stored_hash, hashlib.sha256).hexdigest()[:24], "...")
RFC 5869 case 1 OK: True
files/encrypt v1   231371f9d34ea5cb4e081cde...
files/mac v1       3fd9a30018e7ff1de61abc47...
tokens/sign v1     cacb2cad25a8de3706e25247...
peppered: 9e18d557759cf27ddcb7b5ff ...

HKDFExpand skips the Extract step, which is fine only because the master key is already uniformly random. For a DH output or anything with structure, use the full HKDF (Extract then Expand). The version number in each label (v1) gives you a clean way to rotate: derive v2 keys and migrate.

Passwords to keys

When a passphrase must become an encryption key (a password manager vault, an encrypted backup, the mini project of this course), the pattern is:

text
salt = os.urandom(16)                       stored in the file header, not secret
key  = Argon2id(passphrase, salt, m, t, p)  parameters also stored in the header
data = AES-GCM(key, nonce, plaintext, aad = header)

The cost parameters can be higher than for login hashing, because this runs once per unlock on the user's device, not thousands of times per second on a server. Bitwarden, 1Password, age's passphrase mode and LUKS2 disk encryption follow this design with different algorithm choices (Argon2id in LUKS2 and Bitwarden's option, scrypt in age, PBKDF2 plus a secret key in 1Password).

Peppers

A pepper is a secret key shared by all password hashes and stored outside the database: in a secrets manager, an HSM or the application's configuration, not in the same backup as the hashes. An attacker who steals only the database (by SQL injection, a leaked backup, a misconfigured bucket) can't test a single guess without it.

OWASP describes two ways to apply it:

  • Post-hashing: store HMAC(pepper,Argon2id(pw,salt))\text{HMAC}(\text{pepper}, \text{Argon2id}(pw, salt)), as in the first example.
  • Pre-hashing: hash HMAC(pepper,pw)\text{HMAC}(\text{pepper}, pw) with the password hash. With bcrypt this also fixes the 72-byte limit, but the HMAC output must be Base64-encoded first: raw digests can contain zero bytes, and some bcrypt implementations stop at the first zero byte.
python · try it yourself
import base64, hashlib, hmac
from argon2 import PasswordHasher

PEPPER = bytes.fromhex("5e" * 32)          # lab value; real: 32 bytes from secrets.token_bytes, in a vault/HSM, never in the DB
ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)

def prehash(password):                     # OWASP's pattern: HMAC with the pepper, then Base64 (no NUL bytes)
    return base64.b64encode(hmac.new(PEPPER, password.encode(), hashlib.sha384).digest()).decode()

stored = ph.hash(prehash("lab-only-password"))
print("stored hash starts:", stored[:16], "... (the DB holds this, not the pepper)")
print("login, right password:", ph.verify(stored, prehash("lab-only-password")))
# An attacker with only the database can't even start guessing: every guess needs the pepper.
wrong_pepper = base64.b64encode(hmac.new(b"guess", b"lab-only-password", hashlib.sha384).digest()).decode()
try:
    ph.verify(stored, wrong_pepper)
except Exception as e:
    print("right password, wrong pepper:", type(e).__name__)
print("pre-hash length:", len(prehash("x" * 1000)), "characters, whatever the password length")
stored hash starts: $argon2id$v=19$m ... (the DB holds this, not the pepper)
login, right password: True
right password, wrong pepper: VerifyMismatchError
pre-hash length: 64 characters, whatever the password length

Peppers have costs. If the pepper is lost, every password must be reset; if it leaks, it must be changed, and with pre-hashing that also means resetting every password (OWASP notes this), while post-hashing peppers can be rotated by re-wrapping the stored values. Keep a pepper id with each hash so several peppers can coexist during a rotation. A pepper also doesn't help if the attacker controls the application server, which holds it.

How KDF misuse is detected

  • Fast KDFs on passwords: HKDF(password…), sha256(password).digest() used as an AES key, EVP_BytesToKey (OpenSSL's old enc default: one MD5 iteration), openssl enc -k without -pbkdf2 -iter.
  • Missing domain separation: the same key used for encryption and MAC, or for two services; subkeys derived without labels.
  • Pepper handling: pepper stored in the same database or the same backup as the hashes, hard-coded in source, no rotation plan.
  • Unsafe pre-hashing: raw binary HMAC or SHA output passed to bcrypt.

How it is fixed

  • Passwords: Argon2id (or scrypt, PBKDF2 where FIPS requires) with a random salt and stored parameters.
  • High-entropy secrets: HKDF with a distinct info per purpose, direction and version.
  • Peppers: 32 random bytes in a secrets manager or HSM, referenced by id, applied with HMAC; Base64 before bcrypt.
  • For file encryption with a passphrase, prefer a maintained format (age, libsodium's crypto_pwhash plus secretstream) over a custom one, unless the exercise is to build one.

Pitfalls

  • Thinking a pepper replaces salts: salts are still needed per password.
  • Using Argon2id with tiny parameters "because it's Argon2": the parameters are the security.
  • Deriving encryption and authentication keys with the same label because "they are used together".

Practice

1. A backup tool derives its AES key as sha256(passphrase). What is the risk and the fix?

An attacker with the encrypted backup can test about 101010^{10} passphrases per second per GPU, with no salt, so precomputation works too. Fix: Argon2id (or scrypt) with a random salt and stored parameters, then AES-GCM with the header as AAD.

2. Why is HKDF without a salt acceptable for a 256-bit random master key but not for a password?

The master key is already uniform and unguessable, so HKDF's only job is to separate purposes. A password is guessable, and HKDF is fast, so it does nothing to slow guessing; it needs a slow, salted, memory-hard function.

3. Your database backups are stored in a different cloud account from the application. Where should the pepper live?

In the application's secrets manager or HSM, never in the database or its backups. Then a stolen backup alone doesn't allow guessing.

Test yourself

Which function should turn an X25519 shared secret into session keys?

  1. Argon2id
  2. bcrypt
  3. HKDF
  4. MD5

Where must a pepper be stored?

  1. Next to each hash
  2. In the same table as the salts
  3. Outside the database, in a secrets manager or HSM
  4. In the user's browser

Why must an HMAC pre-hash be Base64-encoded before bcrypt?

  1. To make it longer
  2. Raw digests can contain zero bytes that some bcrypt implementations treat as the end of the input
  3. bcrypt needs ASCII letters only
  4. For speed

What does the info label in HKDF provide?

  1. Secrecy
  2. Domain separation: different labels give independent keys
  3. A salt
  4. Slowness