Rahul Sharma (Editor)

HKDF

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

HKDF is an HMAC based key derivation function that transforms any weak key material into cryptographically strong key material. It can be used, for example, to convert Diffie Hellman exchanged shared secrets into key material suitable for use in encryption, integrity checking or authentication.

Contents

It is formally described in Internet Engineering Task Force RFC 5869. Hugo Krawczyk also described the algorithm in the International Association of Cryptologic Research in 2010.

Mechanism

HKDF extracts a pseudo random key (PRK) using an HMAC hash function (e.g. HMAC-SHA256) on an optional salt and any potentially weak input key material (IKM). It then generates similarly cryptographically strong output key material (OKM) of any desired length by repeatedly generating PRK-keyed hash-blocks and then appending them into the output key material, finally truncating to the desired length.

For added security, the HMAC PRK keyed hash blocks are chained during their generation by prepending the previous hash block to an incrementing 8-bit counter with an optional context string in the middle before being HMACed to generate the current hash block.

Note: HKDF does not amplify entropy but does allow a large source of weaker entropy to be utilised more evenly and effectively.

Uses

HKDF has two primary and potentially independent uses:

1. To "extract" (condense/blend) entropy from a larger random source to provide a more uniformly unbiased and higher entropy but smaller output. e.g. an encryption key. This is done by utilising the diffusion properties of cryptographic MACs.

2. To "expand" the generated output or an already reasonably random input such as an existing shared key into a larger cryptographically independent output, thereby producing multiple keys deterministicly from that initial shared key, so that the same process may produce those same secret keys safely on multiple devices as long as the same inputs are utilised.

These two functions may also be combined and used to form a PRNG to improve a random number generators's potentially-biased output as well as protect it from analysis and help defend the random number generation from malicious inputs.

Example: Python Implementation of HKDF

#!/usr/bin/env python3 import hashlib import hmac from math import ceil hash_len = 32 def hmac_sha256(key, data): return hmac.new(key, data, hashlib.sha256).digest() def hkdf(length, ikm, salt=b"", info=b""): prk = hmac_sha256(salt, ikm) t = b"" okm = b"" for i in range(ceil(length / hash_len)): t = hmac_sha256(prk, t + info + bytes([1+i])) okm += t return okm[:length]

References

HKDF Wikipedia