HKDF Extract and Expand
HKDF, or HMAC-based Extract-and-Expand Key Derivation Function, turns secret input material into one or more cryptographically separate keys. It uses HMAC—a keyed form of a hash function—not to encrypt data, but to create pseudorandom key material that can be safely assigned to different jobs.
The problem HKDF solves
A protocol often starts with one shared secret. For example, a key exchange may produce a single byte string known to both peers. The protocol then needs several keys:
- one for encryption in each direction;
- one for authentication or record integrity;
- one for deriving keys for later sessions;
- perhaps separate keys for different protocol versions or message types.
Using the same secret directly for all of these purposes is poor separation. A key used by one algorithm may have the wrong length or structure for another. More importantly, outputs used in different parts of a protocol should not accidentally overlap or become related in a useful way.
Before HKDF, developers commonly handled this with ad hoc combinations of hashes, concatenated labels, or repeated HMAC calls. Those approaches can work when designed carefully, but they leave important questions to each protocol author: how should uneven or biased input be handled, how should contexts be separated, and how should long output be generated?
HKDF gives those operations a standard two-stage shape:
- Extract turns the input secret into a strong, fixed-length pseudorandom key.
- Expand uses that key and a context string to produce the required amount of output.
Extract: normalize the input secret
The extract stage takes two inputs:
- IKM, or input keying material: the secret bytes available to the protocol;
- salt: optional public or secret bytes that add context to the derivation.
It computes:
PRK = HMAC(salt, IKM)
The result, called the pseudorandom key (PRK), has the fixed length of the selected hash function. With SHA-256, for example, it is 32 bytes.
The salt is the HMAC key in this operation, while the IKM is the HMAC message. If no salt is supplied, HKDF uses a string of zero bytes the length of the hash output. A salt does not need to be secret. A protocol can use a public session value, such as a handshake transcript hash, to make the resulting PRK specific to that session.
The important job of extract is to concentrate the usable unpredictability of the input into a uniform-looking value. Key exchange output is usually already high quality, but it may be longer than needed, have a format imposed by the exchange, or combine several inputs. Extract gives the next stage one well-defined key-sized input.
In contrast, HKDF is not a password-strengthening function. If the IKM is a human password, HKDF does not make guessing it expensive enough; a password-specific function such as Argon2, scrypt, or PBKDF2 is needed first.
Expand: derive labeled outputs
The expand stage takes the PRK, an info value, and the desired output length. info is context metadata: a label such as client encryption key, a direction such as server-to-client, a protocol identifier, or a transcript-derived value.
Conceptually, HKDF-Expand produces a sequence of hash-sized blocks:
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)
...
The blocks are concatenated and truncated to the requested length. The previous block is included in the next HMAC input, so expand can produce more output than one HMAC call while remaining tied to the same PRK. The counter byte distinguishes each block. Standard HKDF limits the output to 255 hash blocks.
A simplified SHA-256 implementation shows the roles, though production code should normally use a vetted HKDF library:
import hashlib
import hmac
def extract(salt, ikm):
if salt is None:
salt = b"\x00" * hashlib.sha256().digest_size
return hmac.digest(salt, ikm, "sha256")
def expand(prk, info, length):
size = hashlib.sha256().digest_size
if length > 255 * size:
raise ValueError("HKDF output too long")
output = bytearray()
previous = b""
for counter in range(1, (length + size - 1) // size + 1):
previous = hmac.digest(
prk, previous + info + bytes([counter]), "sha256"
)
output.extend(previous)
return bytes(output[:length])
Why both stages matter
Extract and expand solve different problems. Extract alone gives one PRK. It does not provide a clean interface for requesting several labeled keys of different lengths. Expand alone can generate output from an existing strong key, but it does not provide extract’s normalization step for general input material.
A protocol normally extracts once, then expands separately for every purpose:
PRK = HKDF-Extract(salt, shared_secret)
client_write_key = HKDF-Expand(PRK, "client write key", 32)
server_write_key = HKDF-Expand(PRK, "server write key", 32)
header_key = HKDF-Expand(PRK, "header protection", 16)
The labels are domain separation: a technique for ensuring that the same underlying secret is used in distinct, explicitly named contexts. Different info values produce outputs intended to be computationally independent, assuming HMAC and its hash function behave as expected. Include direction, algorithm, protocol version, and other relevant context in those labels rather than relying on call order or comments.
HMAC is not encryption here
HMAC is a message-authentication construction. Given a key and message, it produces a fixed-size tag that lets someone with the key verify the message. It is not designed to hide the message, and its output cannot be decrypted to recover one.
HKDF uses HMAC as a secure keyed pseudorandom function. The HMAC inputs are carefully arranged so their outputs behave like fresh random-looking bytes to an attacker who does not know the PRK. Those bytes become encryption keys or other secrets later. HKDF therefore sits before encryption in a protocol: it derives the keys, while an encryption construction such as an AEAD mode uses those keys to provide confidentiality and usually integrity.
If HKDF appears in a handshake trace, configuration option, or library error, the practical interpretation is usually this: one negotiated secret is being converted into several purpose-specific keys, with extract establishing a safe base and expand assigning labeled pieces of key material to the protocol’s separate jobs.