What is HMAC (Hash-based Message Authentication Code)?

HMAC combines a hash function with a secret key to verify both the integrity and authenticity of a message.

HMAC, short for Hash-based Message Authentication Code, is a mechanism that combines a cryptographic hash function with a secret key to produce a code that verifies both the integrity and the authenticity of a message. Unlike a plain hash, which anyone can compute, an HMAC can only be generated or verified by parties that share the secret key, proving the message came from a legitimate sender and was not altered.

The construction wraps a hash function - such as SHA-256, yielding HMAC-SHA256 - around the message and a key using a specific, standardized scheme with inner and outer padding. This design protects against length-extension attacks that would affect naively concatenating a key and message with certain hash functions, making HMAC a robust and well-analyzed approach to message authentication.

HMAC is everywhere in secure communication. APIs use it to sign requests so the server can confirm the caller holds the shared secret and that parameters were not tampered with in transit. Webhooks include an HMAC signature so the receiver can verify the payload genuinely came from the sender. JSON Web Tokens signed with the HS256 algorithm rely on HMAC-SHA256 to guarantee the token was issued by a trusted party.

The security of HMAC depends entirely on keeping the key secret and comparing signatures safely. The shared key must never be exposed in client-side code or logs, and verification should use constant-time comparison to avoid timing attacks. When both sides guard the key properly, HMAC provides strong, efficient assurance that a message is authentic and unmodified.

Examples

  • HMAC-SHA256(message, secret) signing an outgoing API request
  • A webhook X-Signature header the receiver recomputes to verify the payload
  • A JWT signed with HS256 using HMAC-SHA256 for tamper detection

Common questions

How is HMAC different from a regular hash?
A plain hash proves only that data has not changed, and anyone can compute it. HMAC adds a secret key, so it also proves the message came from someone who holds that key - providing authenticity, not just integrity.
Which hash function should HMAC use?
HMAC-SHA256 is a common, secure default. HMAC can be built on other secure hashes too. Avoid pairing it with broken functions like MD5 for security-sensitive uses.
Why compare HMAC signatures in constant time?
A naive comparison that returns early on the first mismatched byte can leak timing information an attacker uses to forge a signature. Constant-time comparison takes the same time regardless of where a mismatch occurs.

Related tools

Related terms for HMAC (Hash-based Message Authentication Code)