๐Ÿ“HKDF

tags

ยง Cryptography

RFC

RFC 5869 - HMAC-based Extract-and-Expand Key Derivation Function (HKDF)

HKDF is a key derivation function (KDF) that uses HMAC to generate new key material.

two main uses:

inputs:

generates:

Algorithm:

  1. generate Pseudo-Random Key (PRK) with HMAC using salt as key, and IKM as data

  2. 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 (IKMB) + 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