← retour aux snippets

HKDF: dériver des clés avec SHA-256 (stdlib)

Implémenter HKDF (RFC 5869) via hmac/sha256 pour dériver des sous-clés.

python security #hkdf#hmac#sha256

objectif

Implémenter HKDF (RFC 5869) via hmac/sha256 pour dériver des sous-clés.

code minimal

import hmac, hashlib

def hkdf_extract(salt: bytes, ikm: bytes) -> bytes:
    return hmac.new(salt or b"\x00"*32, ikm, hashlib.sha256).digest()

def hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes:
    okm, t = b"", b""
    for c in range(1, (length // 32) + (1 if length % 32 else 0) + 1):
        t = hmac.new(prk, t + info + bytes([c]), hashlib.sha256).digest()
        okm += t
    return okm[:length]

prk = hkdf_extract(b"salt", b"input key material")
okm = hkdf_expand(prk, b"context", 42)
print(len(okm) == 42)  # attendu: True

utilisation

key32 = hkdf_expand(hkdf_extract(b"s", b"ikm"), b"api", 32)
print(len(key32) == 32)

variante(s) utile(s)

key = hkdf_expand(hkdf_extract(b"", b"x"), b"", 16)
print(len(key) == 16)

notes

  • Utilisez un salt non vide si possible (random 32 octets).
  • HKDF sépare entropie brute (extract) et dérivation (expand).