How PBKDF2 stretches a password by repeating HMAC

Short answer: PBKDF2 stretches a password by repeating HMAC. For one block, the first value is HMAC of the password and the salt followed by a block counter. Each later value is HMAC of the password and the previous value. The block is the xor of those values. The fragment uses one iteration, so the block is that first HMAC. A password store uses a large iteration count.


What the problem actually asks

A password is a low-entropy secret. A fast hash lets a guesser try many passwords. PBKDF2 makes each guess run the HMAC many times. The salt makes two equal passwords store different strings, and it makes a precomputed table for one salt useless for another. The iteration count is the cost. The function is not memory-hard: a guesser can evaluate the chain with a small amount of memory and can try many passwords in parallel. The fragment uses one iteration so the output is the standard one-iteration block, not a suggested store cost.


What the algorithm guarantees

The same password, salt, count, and length reproduce the same bytes. A different salt reproduces different bytes. With one iteration, the first 32 bytes are HMAC-SHA-256 of salt || 00000001. Raising the count multiplies the work for the honest verifier and for the guesser by about the same factor. It does not add a large memory requirement.


The working steps

  1. Set the block counter to 1 as a four-byte big-endian integer.
  2. Compute HMAC of the password and the salt followed by that counter.
  3. Repeat HMAC, using the previous HMAC output as the next message, and xor the outputs together.
  4. Stop after the chosen number of iterations. Ask for further blocks by incrementing the counter if more than 32 bytes are required.

Approaches that look simpler and fail

Approach Why it fails as a memory-hard password hash
Use one iteration in a password store One iteration is the test vector. A store chooses a count that makes a guess expensive.
Omit the salt Equal passwords then store equal strings, and one precomputed table applies to every user.
Expect the iteration count to demand a large memory The chain stores a hash-sized state. A memory-hard function such as scrypt fills a table.
Encrypt the password with the result and throw the salt away Verification needs the salt and the count. They are stored beside the derived bytes.

scrypt wraps this construction around a large table. PBKDF2 is the iteration.


A working example

This Python fragment runs PBKDF2-HMAC-SHA-256 for one iteration on the password password and the salt salt. It prints 120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b.

import struct

def _primes(k: int) -> list[int]:
    out: list[int] = []
    n = 2
    while len(out) < k:
        if all(n % p for p in out if p * p <= n):
            out.append(n)
        n += 1
    return out

def _isqrt(n: int) -> int:
    x = int(n ** 0.5)
    while x * x > n:
        x -= 1
    while (x + 1) * (x + 1) <= n:
        x += 1
    return x

def _icbrt(n: int) -> int:
    x = int(round(n ** (1 / 3)))
    while x * x * x > n:
        x -= 1
    while (x + 1) ** 3 <= n:
        x += 1
    return x

_PS = _primes(64)
_H256 = [_isqrt(p << 64) & 0xFFFFFFFF for p in _PS[:8]]
_K256 = [_icbrt(p << 96) & 0xFFFFFFFF for p in _PS]

def _rotr(x: int, n: int) -> int:
    return ((x >> n) | (x << (32 - n))) & 0xFFFFFFFF

def sha256(data: bytes) -> bytes:
    h = _H256[:]
    bit_len = len(data) * 8
    msg = data + b"\x80"
    msg += b"\x00" * ((56 - len(msg) % 64) % 64)
    msg += struct.pack(">Q", bit_len)
    for off in range(0, len(msg), 64):
        w = list(struct.unpack(">16I", msg[off : off + 64]))
        for i in range(16, 64):
            s0 = _rotr(w[i - 15], 7) ^ _rotr(w[i - 15], 18) ^ (w[i - 15] >> 3)
            s1 = _rotr(w[i - 2], 17) ^ _rotr(w[i - 2], 19) ^ (w[i - 2] >> 10)
            w.append((w[i - 16] + s0 + w[i - 7] + s1) & 0xFFFFFFFF)
        a, b, c, d, e, f, g, hh = h
        for i in range(64):
            s1 = _rotr(e, 6) ^ _rotr(e, 11) ^ _rotr(e, 25)
            ch = (e & f) ^ (~e & g)
            t1 = (hh + s1 + ch + _K256[i] + w[i]) & 0xFFFFFFFF
            s0 = _rotr(a, 2) ^ _rotr(a, 13) ^ _rotr(a, 22)
            maj = (a & b) ^ (a & c) ^ (b & c)
            t2 = (s0 + maj) & 0xFFFFFFFF
            hh, g, f, e, d, c, b, a = g, f, e, (d + t1) & 0xFFFFFFFF, c, b, a, (t1 + t2) & 0xFFFFFFFF
        h = [(x + y) & 0xFFFFFFFF for x, y in zip(h, (a, b, c, d, e, f, g, hh))]
    return struct.pack(">8I", *h)

def hmac_sha256(key: bytes, msg: bytes) -> bytes:
    if len(key) > 64:
        key = sha256(key)
    key = key.ljust(64, b"\x00")
    outer = bytes(b ^ 0x5C for b in key)
    inner = bytes(b ^ 0x36 for b in key)
    return sha256(outer + sha256(inner + msg))

def pbkdf2_sha256(password: bytes, salt: bytes, rounds: int, length: int) -> bytes:
    out = b""
    block_index = 1
    while len(out) < length:
        u = hmac_sha256(password, salt + struct.pack(">I", block_index))
        acc = int.from_bytes(u, "big")
        for _ in range(rounds - 1):
            u = hmac_sha256(password, u)
            acc ^= int.from_bytes(u, "big")
        out += acc.to_bytes(32, "big")
        block_index += 1
    return out[:length]

derived = pbkdf2_sha256(b"password", b"salt", 1, 32)
assert derived.hex() == "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b"
print(derived.hex())

Where it is used

WPA2 turns a passphrase into a key with PBKDF2-HMAC-SHA1, and password stores such as Django’s historical default use PBKDF2-HMAC-SHA-256. The iteration count is the cost. A memory-hard store uses scrypt or Argon2.


When you can drop this algorithm

Drop a one-iteration PBKDF2 as a password store. Keep PBKDF2 where the iteration count is an explicit cost and a memory-hard alternative is not required. Keep the one-iteration case as the test vector.


Why this stays published

We publish this so a search for PBKDF2 returns the iterated HMAC and the one-iteration test block. PBKDF2 xors a chain of HMAC outputs whose first input is the salt and a block counter, and the iteration count is the cost.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *