๐HKDF
HKDF is a key derivation function (KDF) that uses HMAC to generate new key material.
two main uses:
- given a large source of weak entropy, condense it and provide a smaller source of stronger entropy. (e.g., generating an encryption key)
- Note that HKDF does not amplify entropy, but allows a larger source of weak entropy to be utilized more evenly.
- given a small source of strong entropy, expand it and generate a large number of independent keys. This can be done on multiple devices independently and produce deterministic results. (e.g., producing multiple keys from a single key exchanged with diffie-hellman)
inputs:
- salt (acts as a key)
- IKM (input key material, possibly weak entropy) (IKM_A)
- optional context string (IKM_B)
generates:
- OKM (output key material of the given length)
Algorithm:
- generate Pseudo-Random Key (PRK) with HMAC using salt as key, and IKM as data
- use HMAC to repeatedly generate new blocks until enough length is generated
- for key, use PRK
- for data, use HMAC from previous iteration + optional context (IKM_B) + incrementing 8-bit counter
Example Python implementation:
#!/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: int, ikm, salt: bytes = b"", info: bytes = b"") -> bytes:
if len(salt) == 0:
salt = bytes([0] * hash_len)
prk = hmac_sha256(salt, ikm)
okm = b""
t = b""
for i in range(ceil(length / hash_len)):
t = hmac_sha256(prk, t + info + bytes([1 + i]))
okm += t
return okm[:length]
Backlinks
- ๐ ยง Cryptography