HMAC (Hash-based Message Authentication Code)
Cryptographic mechanism for message integrity checking and authentication: combines a message with a secret key using a hash function, so that only parties with the key can verify the code.
HMAC (Hash-based Message Authentication Code) is a mechanism for simultaneously verifying integrity (has the message been altered?) and authenticity (does the message come from the expected sender?). It combines a cryptographic hash function with a secret key.
How HMAC Works
HMAC(K, M) = H(K XOR opad || H(K XOR ipad || M))
Where:
K = secret key
M = message
H = hash function (e.g., SHA-256)
ipad = inner pad (repeated 0x36)
opad = outer pad (0x5c repeated)
In practice: HMAC calculates a deterministic "fingerprint" from the key and the message. Only those who know the same key can:
- Calculate a valid HMAC
- Verify a received HMAC
HMAC vs. simple hash function
Problem with simple hash: SHA-256(message) - anyone can compute the hash and create a new valid hash for a manipulated message.
HMAC solution: HMAC-SHA256(key, message) - without the secret key, no one can create or verify a valid MAC.
Length Extension Attack: Certain hash functions (MD5, SHA-1, SHA-256) are vulnerable to length extension attacks. HMAC protects against this with its double hash structure.
Practical Use
API Signatures: Almost all modern APIs (AWS, Stripe, GitHub Webhooks, Twilio) use HMAC-SHA256 for request authentication:
Signature = HMAC-SHA256(API_SECRET, timestamp + method + path + body)
JWT (JSON Web Tokens): HMAC-SHA256 (HS256) is one of the most common JWT signing algorithms—although asymmetric signatures (RS256, ES256) should be preferred for critical applications.
DKIM: Email signing uses HMAC-like signatures with private keys.
TLS: HMAC is used in the TLS record layer for message integrity (in TLS 1.2; TLS 1.3 uses AEAD modes that incorporate MACs).
Password Hashing Algorithms: PBKDF2 (Password-Based Key Derivation Function 2) uses HMAC internally for its iteration.
Security Recommendations
- Use HMAC-SHA-256 or HMAC-SHA-512 (MD5 and SHA-1 are obsolete)
- Keys should be at least as long as the hash output (256 bits for SHA-256)
- Rotate keys regularly
- Use constant-time comparison during verification (prevents timing attacks)
- Do not use HMAC for password hashing—use bcrypt/Argon2 instead
HMAC vs. Digital Signature
| HMAC | Digital Signature | |
|---|---|---|
| Key type | Symmetric (same key) | Asymmetric (private/public) |
| Speed | Very fast | Slower |
| Non-repudiation | No (both parties know the key) | Yes (only the sender has the private key) |
| Typical use | API authentication, integrity between two trusting parties | Digital documents, certificates, code signing |