What is HMAC?
HMAC (Hash-based Message Authentication Code) is a cryptographic technique that combines a secret key with a hash function to produce a message authentication code. It provides both integrity (the message hasn't been tampered with) and authenticity (the message came from someone who knows the secret key).
HMAC is defined in RFC 2104 and is used in TLS, JWT signatures (HS256/HS384/HS512), webhook verification, API authentication, and many other security protocols.
How HMAC works
HMAC(K, m) = H((K' XOR opad) || H((K' XOR ipad) || m))
Where:
H = hash function (SHA-256, SHA-512, etc.)
K = secret key (padded/hashed to block size → K')
m = message
ipad = 0x36 repeated (inner padding)
opad = 0x5C repeated (outer padding)
Algorithm comparison
| Algorithm | Output size | Security | Use case | Status |
|---|---|---|---|---|
| HMAC-SHA256 | 256 bits (64 hex) | 128-bit | JWT HS256, webhooks, API auth | Recommended |
| HMAC-SHA384 | 384 bits (96 hex) | 192-bit | JWT HS384, high security | Recommended |
| HMAC-SHA512 | 512 bits (128 hex) | 256-bit | JWT HS512, maximum security | Recommended |
| HMAC-SHA1 | 160 bits (40 hex) | 80-bit | Legacy systems, Git | Legacy only |
| HMAC-MD5 | 128 bits (32 hex) | 64-bit | Non-security checksums | Avoid |
Common use cases
| Use case | Algorithm | Example |
|---|---|---|
| JWT signatures | HMAC-SHA256/384/512 | HS256, HS384, HS512 in JWT header |
| Webhook verification | HMAC-SHA256 | GitHub, Stripe, Shopify webhooks |
| API authentication | HMAC-SHA256 | AWS Signature v4, HMAC-based API keys |
| Cookie integrity | HMAC-SHA256 | Signed session cookies |
| TLS record MAC | HMAC-SHA256 | TLS 1.2 record layer (deprecated in 1.3) |
HMAC vs plain hash
A plain hash (e.g. SHA-256) of a message can be computed by anyone — it provides no authentication. HMAC requires the secret key, so only parties that know the key can produce or verify the MAC. This prevents length extension attacks that affect plain SHA-256 used naively.
References
- RFC 2104 — HMAC: Keyed-Hashing for Message Authentication
- RFC 4868 — Using HMAC-SHA-256/384/512 with IPsec
- NIST FIPS 198-1 — The Keyed-Hash Message Authentication Code
