Glossary

What Is HMAC? (Hash-Based Message Authentication Code)

HMAC (Hash-based Message Authentication Code) is a specific construction that combines a cryptographic hash function with a secret key to produce a message authentication code. Unlike a plain hash, HMAC requires knowledge of the secret key to verify — providing both integrity checking and authenticity.

How HMAC Works

HMAC(key, message) = H((key ⊕ opad) || H((key ⊕ ipad) || message)), where H is the hash function, opad and ipad are fixed padding constants, and ⊕ is XOR. In practice, you provide a secret key and message; the output is a fixed-length tag that changes completely if either the key or message changes.

HMAC vs Plain Hash

A plain hash (e.g., SHA-256) of a message can be computed by anyone — it proves integrity but not authenticity. HMAC requires the secret key to generate or verify the tag. An attacker who can modify a message cannot produce a valid HMAC without knowing the key, making HMAC suitable for API request signing and webhook verification.

Common HMAC Applications

HMAC-SHA256 is used to sign JWT tokens (HS256), authenticate API requests in AWS Signature v4, verify webhook payloads from Stripe, GitHub, and Shopify, validate cookie session data, and in TOTP (Time-based One-Time Password) algorithms like Google Authenticator.

Timing Attacks and Safe Comparison

When verifying an HMAC, always use a constant-time comparison function (such as crypto.timingSafeEqual in Node.js). Standard string equality (===) short-circuits on the first differing byte, potentially leaking information about how many bytes matched. Timing attacks can reconstruct a valid HMAC byte by byte.