HKDF

HKDF is a simple key derivation function (KDF) based on a hash-based message authentication code (HMAC). It was initially proposed by its authors as a building block in various protocols and applications, as well as to discourage the proliferation of multiple KDF mechanisms. The main approach HKDF follows is the "extract-then-expand" paradigm, where the KDF logically consists of two modules: the first stage takes the input keying material and "extracts" from it a fixed-length pseudorandom key, and then the second stage "expands" this key into several additional pseudorandom keys (the output of the KDF).
It can be used, for example, to convert shared secrets exchanged via Diffie–Hellman into key material suitable for use in encryption, integrity checking or authentication.
It is formally described in the RFC 5869. One of its authors also described the algorithm in a companion paper in 2010.
In November, 2011, NIST released SP 800-56C, superseded in April, 2018 by SP 800-56C Rev. 1. Both state that HKDF's specification is a conforming scheme and point to its paper for the rationale for the recommendations' extract-and-expand mechanisms.
There are implementations of HKDF for C#, Go, Java, JavaScript, Perl, PHP, Python, Ruby and other languages.
Mechanism.
HKDF extracts a pseudorandom key (PRK) using an HMAC hash function (e.g. HMAC-SHA256) on an optional salt (acting as a key) and any potentially weak input key material (IKM) (acting as data). 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 PRK-keyed HMAC-hashed 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 hashed by HMAC 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:
These two functions may also be combined and used to form a PRNG to improve a random number generator's potentially-biased output, as well as to protect it from analysis and help defend the random number generation from malicious inputs.
Example: Python implementation.
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:
 """Key derivation function"""
 if len(salt) == 0:
 salt = bytes([0] * hash_len)
 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]