HMAC (Hash-based Message Authentication Code)
A cryptographic construction combining a hash function with a secret key to produce a message authentication code, verifying both integrity and authenticity.
HMAC (Hash-based Message Authentication Code) is a construction for creating a message authentication code using a cryptographic hash function combined with a secret key. It provides both integrity verification and authentication of the message.
Construction
HMAC(K, m) = H((K' XOR opad) || H((K' XOR ipad) || m))
Where:
- H = Hash function (SHA-256, etc.)
- K = Secret key
- K' = Key padded to block size
- opad = 0x5c repeated
- ipad = 0x36 repeated
- m = Message
Usage Example
import hmac
import hashlib
# Create HMAC
key = b"secret_key"
message = b"data to authenticate"
mac = hmac.new(key, message, hashlib.sha256).hexdigest()
# Verify HMAC (use constant-time comparison!)
received_mac = "..."
expected_mac = hmac.new(key, message, hashlib.sha256).hexdigest()
if hmac.compare_digest(received_mac, expected_mac):
print("Valid!")
Security Properties
- Integrity: Detects any modification to message
- Authentication: Only key holder can create valid MAC
- No length extension: Unlike raw H(key || message)
Common Applications
- API request signing
- Cookie/token authentication
- JWT signatures (HS256 = HMAC-SHA256)
- Password storage (with slow hash like PBKDF2)
HMAC vs Encryption
// HMAC: Provides authentication, NOT confidentiality
// Anyone can read the message, but only key holder can create valid MAC
// For confidentiality + authenticity:
// Use authenticated encryption (AES-GCM) or Encrypt-then-MAC