Course contentsShow
← Security
Lesson 219 of 3,0525. Cryptographic Hashing and MACsFree lesson

HMAC Key Management and Key Derivation

Explore proper HMAC key generation, storage, and derivation techniques for secure authentication systems.

HMAC Key Management and Key Derivation

You'll learn how to properly generate, store, and derive HMAC keys to keep your authentication systems secure.

The Core Challenge

HMAC is only as secure as the key that powers it. A strong HMAC construction means nothing if your key is weak, predictable, or poorly managed. Just like a vault with an unbreakable door but a key hidden under the doormat, poor key management undermines all cryptographic protection.

Key Generation Rules

Never use passwords directly as HMAC keys. Passwords are typically short and lack sufficient entropy (randomness). Instead:

  • Generate HMAC keys using cryptographically secure random number generators
  • Aim for key sizes matching your hash function's output (256 bits for SHA-256, 512 bits for SHA-512)
  • While HMAC accepts any key length, shorter keys reduce security

Key Derivation for HMAC

When you must derive HMAC keys from passwords or other keys, use proper Key Derivation Functions (KDFs) like PBKDF2, HKDF, or Argon2:

master_key = random_bytes(32)
hmac_key = HKDF(master_key, salt, context_info)

This transforms a single master key into multiple purpose-specific HMAC keys safely. Each derived key remains cryptographically independent—compromising one doesn't expose others.

Secure Storage

Store HMAC keys with the same care as encryption keys:

  • Use hardware security modules (HSMs) or key management services for production
  • Never hardcode keys in source code
  • Apply access controls limiting which processes can read keys
  • Rotate keys periodically, especially after suspected compromise

Key Separation

Derive separate HMAC keys for different purposes (user authentication, API signing, message integrity) even from the same master key. This prevents cross-protocol attacks where an HMAC from one context could be replayed in another.

Key Takeaway: HMAC security depends entirely on unpredictable, properly generated keys—use cryptographic random generators for keys, never passwords directly, and employ KDFs when derivation is necessary.