HKDF

Definition

HKDF (HMAC-based Extract-and-Expand Key Derivation Function) is a cryptographic key derivation function that uses HMAC (Hash-based Message Authentication Code) as its core building block. It is designed to securely derive strong cryptographic keys from a source of entropy, such as a shared secret or a master key. HKDF is widely used in protocols like TLS and IPSec to ensure that derived keys are independent and have the desired properties for secure communications.

Secure Settings Example

import hashlib
import hmac
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.backends import default_backend

# Secure HKDF configuration
hkdf = HKDF(
    algorithm=hashlib.sha256(),
    length=32,  # Desired length of the derived key
    salt=b'secure_salt_value',  # Use a strong, unique salt
    info=b'contextual_info',  # Optional context-specific information
    backend=default_backend()
)

derived_key = hkdf.derive(b'input_key_material')

Insecure Settings Example

import hashlib
import hmac
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.backends import default_backend

# Insecure HKDF configuration
hkdf = HKDF(
    algorithm=hashlib.sha1(),  # Using a weak hash function
    length=16,  # Insufficient key length for strong security
    salt=None,  # Missing salt makes the key derivation vulnerable
    info=None,  # Lack of context-specific information
    backend=default_backend()
)

derived_key = hkdf.derive(b'input_key_material')