What is HMAC
HMAC (Hash-based Message Authentication Code) is a construction that combines a hash function with a secret key to produce a fixed-size authentication tag. Unlike a plain hash, which anyone can compute, an HMAC can only be computed and verified by parties who know the secret key. It provides two guarantees: integrity (the message has not been altered) and authenticity (the message was created by someone with the key).
How it works
HMAC is defined as:
HMAC(key, message) = hash((key XOR opad) || hash((key XOR ipad) || message))
The key is XORed with two fixed padding values (ipad and opad), and the message is hashed twice. This nested structure prevents length extension attacks -- a vulnerability where an attacker who knows hash(message) can compute hash(message || extra) without knowing the message. HMAC's double-hashing design makes this impossible.
The most common variant is HMAC-SHA-256, which uses SHA-256 as the underlying hash function and produces a 256-bit (32-byte) tag. HMAC-SHA-512 and HMAC-SHA-384 are used when higher security margins are desired.
To verify a message, the receiver computes the HMAC over the received message using the shared key and compares it to the tag sent by the sender. Comparison must use constant-time equality to prevent timing side-channel attacks. If the tags match, the message is authentic and unmodified.
HMAC is used extensively in practice: JWTs (HS256 algorithm), API authentication (AWS Signature v4), cookie signing, webhook verification, and key derivation (HKDF is built on HMAC). It differs from a digital signature in that both parties share the same secret key -- there is no public/private key distinction.
Why it matters
HMAC is the standard way to authenticate messages when both parties share a secret key. It is simpler and faster than digital signatures, making it the right choice for server-to-server communication, token verification, and any scenario where symmetric key authentication suffices.
See How Hashing Works and How Symmetric Encryption Works for the full context of hash functions and keyed authentication.