arthrop0d

Brief articles on varied topics.

HKDF Extract-and-Expand Key Derivation

cryptographycomputer security

HKDF is a two-stage construction that first turns secret input material into a stable pseudorandom key, then derives one or more context-specific keys from it. Its name means HMAC-based Extract-and-Expand Key Derivation Function: HMAC is a keyed hash construction used here as the underlying secure building block.

The problem HKDF solves

Applications often begin with secret material that is usable but inconvenient. It might be a Diffie–Hellman shared secret, a pre-shared key, or several pieces of secret input concatenated together. That input may have uneven quality: some parts may be predictable, some may have more uncertainty than others, and its length may not match the key size an algorithm requires.

Without a disciplined construction, an application might hash the input once and use the result everywhere. That creates several problems:

HKDF addresses these concerns by separating two jobs:

  1. Extract secret input into one fixed-length pseudorandom key.
  2. Expand that key into as many purpose-specific outputs as the application needs.

This separation is useful even when the original secret already looks random. It gives the protocol a consistent point at which to combine inputs and a clear mechanism for deriving unrelated keys.

Stage one: extract

The extract step takes input key material (IKM), meaning the secret bytes available to the application, and an optional salt, which is usually public randomness or a protocol-specific value. It computes:

PRK = HMAC(salt, IKM)

The result, called the pseudorandom key (PRK), has the fixed length of the selected hash function. With HMAC-SHA-256, for example, the PRK is 32 bytes.

The salt is the HMAC key in this operation. It does not have to be secret. A fresh, public salt can make extraction robust across repeated or related inputs; a protocol may also use a known salt or combine a prior secret into it. If no salt is supplied, HKDF uses a string of zero bytes whose length is the hash function’s output length. That is different from omitting the extract step entirely.

Extraction is primarily about consolidating and conditioning the input. It produces a value with the hash function’s full output format, rather than trying to produce application keys directly. It does not create entropy from nothing: if the IKM is a human password with low uncertainty, HKDF does not make password guessing expensive. Passwords need a password-specific, deliberately slow function such as Argon2, scrypt, or PBKDF2 before they are used for this kind of key derivation.

Stage two: expand

The expand step takes the PRK, a requested output length, and an info value. info is non-secret context that identifies what the derived bytes are for: for example, client-to-server encryption, a protocol version, or a channel identifier.

HKDF generates blocks using HMAC again:

T(0) = empty
T(1) = HMAC(PRK, T(0) || info || 0x01)
T(2) = HMAC(PRK, T(1) || info || 0x02)
T(3) = HMAC(PRK, T(2) || info || 0x03)
...

Here || means concatenation, and 0x01, 0x02, and so on are one-byte counters. HKDF concatenates these blocks and truncates the result to the requested length. The counter is one reason a single PRK can produce more output than the hash function’s normal digest size; in the standard construction, the maximum is 255 hash-sized blocks.

A compact implementation using Python’s standard library looks like this:

import hashlib
import hmac


def hkdf_extract(ikm, salt=b""):
    hash_name = "sha256"
    digest_size = hashlib.new(hash_name).digest_size
    if not salt:
        salt = bytes(digest_size)
    return hmac.new(salt, ikm, hash_name).digest()


def hkdf_expand(prk, info, length):
    hash_name = "sha256"
    digest_size = hashlib.new(hash_name).digest_size
    if length > 255 * digest_size:
        raise ValueError("requested output is too long")

    blocks = []
    previous = b""
    for counter in range(1, (length + digest_size - 1) // digest_size + 1):
        previous = hmac.new(
            prk, previous + info + bytes([counter]), hash_name
        ).digest()
        blocks.append(previous)
    return b"".join(blocks)[:length]

Production code should normally use a well-tested HKDF implementation supplied by its cryptographic library rather than maintaining its own.

Deriving several independent keys

The application extracts once, then expands separately for each purpose. It gives each derivation a distinct info value and requests the exact length required:

PRK = HKDF-Extract(salt, shared_secret)

enc_key = HKDF-Expand(PRK, "protocol v1 | encryption", 32)
mac_key = HKDF-Expand(PRK, "protocol v1 | authentication", 32)
client_iv = HKDF-Expand(PRK, "protocol v1 | client IV", 12)

The labels must be unambiguous and should include relevant context, such as the protocol version, direction, or session identifier. Two different labels produce outputs that are computationally independent: knowing one derived key should not provide a practical way to calculate another, assuming HMAC and the hash function remain secure. This property is called key separation.

An application can also request one long output and split it into fields, but separate labeled expansions make the intent clearer and reduce the risk that a later change reuses bytes for the wrong purpose. The info value is not a password and does not need to be secret; its job is to prevent accidental overlap between uses.

Where the term appears

HKDF commonly appears in key-exchange and secure-channel code. A log mentioning HKDF-Extract, an info label, or a “derived traffic key” usually means that an earlier shared secret is being converted into directional encryption keys, IVs, or other session material. The important design pattern is the boundary between the two stages: extract once to normalize secret material, then expand with explicit labels to separate every use.

← All articles