What is HMAC?

HMAC (Hash-based Message Authentication Code) is a cryptographic technique that combines a secret key with a hash function to verify both the integrity and authenticity of a message. It ensures that data has not been tampered with and comes from a trusted source. The algorithm works by processing the secret key through two rounds of hashing with inner and outer padding (ipad and opad), computed as HMAC(K, m) = H((K' ⊕ opad) || H((K' ⊕ ipad) || m)), where H is the underlying hash function and K' is the key derived from K. This double-hashing construction is what makes HMAC resistant to length extension attacks and provides provable security guarantees under standard cryptographic assumptions.

Quick Facts

Full NameHash-based Message Authentication Code
Created1996 (RFC 2104)
SpecificationOfficial Specification

How It Works

HMAC was published in 1996 by Mihir Bellare, Ran Canetti, and Hugo Krawczyk, and is formally defined in RFC 2104 and FIPS 198-1. The construction works in three steps: first, the secret key is padded or hashed to match the hash function's block size; then, the message is hashed together with the key XORed with an inner pad (0x36 repeated); finally, the result is hashed again with the key XORed with an outer pad (0x5C repeated). This nested structure ensures that even if the underlying hash function has weaknesses (as with MD5 or SHA-1), the HMAC construction remains more secure. HMAC can use any cryptographic hash function — HMAC-SHA256 and HMAC-SHA512 are the most widely deployed today. The resulting code is a fixed-size value (e.g., 256 bits for HMAC-SHA256) that changes completely if either the message or key is modified by even a single bit. HMAC is a fundamental building block in TLS/SSL handshakes, OAuth and API authentication schemes, JWT (JSON Web Token) HS256/HS384/HS512 signatures, webhook payload verification (used by Stripe, GitHub, Shopify), and key derivation functions like HKDF and PBKDF2.

Key Characteristics

  • Combines secret key with hash function
  • Provides both integrity and authenticity
  • Resistant to length extension attacks
  • Can use any hash function (SHA-256, SHA-512)
  • Fixed-size output regardless of input
  • Requires shared secret between parties

Common Use Cases

  1. API authentication: signing HTTP requests with HMAC-SHA256 to verify the identity of the caller and prevent request tampering (used by AWS Signature V4, Stripe, Twilio)
  2. JWT signing: generating HS256/HS384/HS512 JSON Web Token signatures for stateless authentication in web applications and microservices
  3. Webhook verification: validating incoming webhook payloads from services like GitHub, Stripe, Shopify, and Slack by comparing HMAC signatures
  4. Message integrity in transit: ensuring data exchanged between systems has not been altered, used in TLS record layer and IPsec protocols
  5. Secure cookie signing: preventing cookie tampering in web frameworks by attaching HMAC signatures to session cookies
  6. Key derivation (HKDF, PBKDF2): using HMAC as the pseudorandom function in standardized key derivation algorithms for generating cryptographic keys from passwords or shared secrets
  7. OAuth 1.0 request signing: creating base string signatures for OAuth-authenticated API requests

Example

loading...
Loading code...

Frequently Asked Questions

What is the difference between HMAC and a regular hash?

A regular hash only provides data integrity (detecting if data was modified), while HMAC provides both integrity and authenticity (verifying the data came from a trusted source with the secret key). HMAC uses a secret key mixed with the hash function, so only parties with the key can generate or verify the HMAC value.

Why is HMAC more secure than simply hashing a message with a key?

Simply concatenating a key with a message before hashing (e.g., hash(key + message)) is vulnerable to length extension attacks, where attackers can append data to the message without knowing the key. HMAC's double-hashing construction with inner and outer padding specifically prevents this attack and provides proven security guarantees.

Which hash algorithm should I use with HMAC?

HMAC-SHA256 is the most widely recommended choice, offering a good balance of security and performance. HMAC-SHA512 provides extra security margin for highly sensitive applications. Avoid HMAC-MD5 and HMAC-SHA1 for new implementations, though they remain more secure than the underlying hash functions when used in HMAC construction.

How is HMAC used in API authentication?

In API authentication, the client creates an HMAC signature by hashing request details (method, path, timestamp, body) with a shared secret key. The server recreates the same HMAC using its copy of the secret key and compares it to the received signature. If they match, the request is authenticated and hasn't been tampered with.

What happens if the HMAC secret key is compromised?

If the secret key is compromised, attackers can forge valid HMAC signatures for any message, completely bypassing the authentication. You should immediately rotate (change) the compromised key and invalidate all tokens or signatures created with the old key. Use proper key management practices like secure storage and regular rotation to minimize this risk.

How does HMAC compare to digital signatures (RSA, ECDSA)?

HMAC uses a shared symmetric secret key, meaning both the sender and receiver must possess the same key. Digital signatures use asymmetric key pairs (public/private), where only the private key holder can sign but anyone with the public key can verify. HMAC is faster and simpler for trusted party-to-party communication, while digital signatures provide non-repudiation (the signer cannot deny having signed) and are better for scenarios where the verifier should not be able to forge signatures.

What are best practices for HMAC key management?

Use cryptographically random keys of at least the same length as the hash output (e.g., 256 bits for HMAC-SHA256). Store keys securely using environment variables, secrets managers (AWS Secrets Manager, HashiCorp Vault), or hardware security modules (HSMs). Rotate keys periodically and implement key versioning to allow graceful transitions. Never hardcode keys in source code or transmit them over insecure channels. Use constant-time comparison functions when verifying HMAC values to prevent timing attacks.

Related Tools

Related Terms

Related Articles