Hash-based Message Authentication Code (HMAC)
A specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key.
A Hash-based Message Authentication Code (HMAC) is a cryptographic algorithm that combines a hash function (like MD5, SHA-1, or SHA-256) with a secret key to guarantee both data integrity and authenticity.
When you send a message along with its HMAC, the receiver (who must also possess the secret key) can recalculate the HMAC and verify that the message wasn't altered in transit and that it indeed originated from someone holding the secret key.
How HMAC Works
Unlike simply hashing data (e.g., hash(message + secret)), which is vulnerable to length extension attacks, HMAC uses a more complex nested hashing process designed specifically to resist these vulnerabilities:
HMAC(K, m) = H((K ⊕ opad) || H((K ⊕ ipad) || m))
Where:
His a cryptographic hash functionKis the secret keymis the message to be authenticated||denotes concatenation⊕denotes bitwise exclusive or (XOR)opadandipadare specific padding constants
Common Use Cases
- JSON Web Tokens (JWTs): The
HS256algorithm used for signing JWTs is actually HMAC-SHA-256. - API Authentication: Many APIs (like AWS or Stripe) use HMAC to sign requests. The client calculates an HMAC of the request parameters using their API Secret Key and sends it in an HTTP header. The server recalculates it and verifies they match.
- Webhooks: When a service like GitHub or Stripe sends a webhook to your server, they often include an HMAC signature in the headers so you can verify the payload wasn't spoofed by an attacker.