How HKDF extracts and expands a shared secret

Short answer: HKDF-SHA-256 turns a shared secret into key bytes of a chosen length. Extract sets the pseudorandom key to HMAC of the salt and the input keying material. Expand appends HMAC of that key, the previous block, the info string, and a counter, starting from an empty previous block and a counter of 1. An empty salt is replaced by 32 zero bytes.


What the problem actually asks

A Diffie-Hellman result is a group element, not yet a set of symmetric keys. HKDF extracts a key from it and expands that key into the lengths the next algorithms ask for. The info string separates two uses of the same shared secret, such as a sending key and a receiving key. HKDF does not stretch a password. The input is assumed to have the entropy of a fresh shared secret. A password goes through PBKDF2 or scrypt first.


What the algorithm guarantees

The same input, salt, info, and length reproduce the same bytes. A different info string produces different bytes from the same extract step. The RFC 5869 case uses 22 bytes of 0x0b, a 13-byte salt, a 10-byte info string, and a 42-byte output. The fragment matches that case. The extract step is one HMAC. The expand step is one HMAC per 32 bytes of output.


The working steps

  1. If the salt is empty, use 32 zero bytes.
  2. Set the pseudorandom key to HMAC-SHA-256 of the salt and the input.
  3. Set the previous block to empty and the counter to 1.
  4. Append HMAC of the pseudorandom key and previous || info || counter, then increment the counter, until the requested length is reached.

Approaches that look simpler and fail

Approach Why it fails as a password hash
Feed a password straight into HKDF Extract-and-expand does not add an iteration cost or a memory cost. A password needs that cost.
Use one info string for two different keys The info string is the label that separates the outputs. The same label repeats the output.
Skip extract and expand the raw shared secret The two steps are the construction. Expanding the raw secret is a different function.
Treat the output as an authenticator of a message HKDF derives keys. HMAC authenticates a message.

PBKDF2 stretches a password. HKDF derives keys from a secret that already has entropy.


A working example

This Python fragment runs the RFC 5869 HKDF-SHA-256 test case. It prints 3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865.

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 hkdf_sha256(ikm: bytes, salt: bytes, info: bytes, length: int) -> bytes:
    if not salt:
        salt = b"\x00" * 32
    prk = hmac_sha256(salt, ikm)
    out = b""
    block = b""
    counter = 1
    while len(out) < length:
        block = hmac_sha256(prk, block + info + bytes([counter]))
        out += block
        counter += 1
    return out[:length]

ikm = bytes([0x0B]) * 22
salt = bytes(range(13))
info = bytes(range(0xF0, 0xFA))
derived = hkdf_sha256(ikm, salt, info, 42)
assert derived.hex() == "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
print(derived.hex())

Where it is used

The TLS 1.3 key schedule and the Signal protocol derive session keys with HKDF. Extract turns the handshake secret into a pseudorandom key; expand labels each output, such as a traffic key. A password does not go straight into HKDF.


When you can drop this algorithm

Drop HKDF as a password store. Keep it where a shared secret, typically a Diffie-Hellman result, has to become one or more symmetric keys and the info string labels each use.


Why this stays published

We publish this so a search for HKDF returns the extract step, the expand step, and the RFC 5869 output. HKDF-SHA-256 extracts a pseudorandom key with HMAC and expands it into labeled key bytes one counter block at a time.

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

Leave a Reply

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