HMAC

Also known as: Hash-based message authentication code

On this page 7

HMAC, the hash-based message authentication code, is a construction that combines a secret key with a cryptographic hash function to produce a short tag proving that a message came from a holder of the key and was not modified in transit. In cryptography, HMAC is the standard way to obtain integrity and authenticity with symmetric keys, and it underpins protocols such as TLS, IPsec, SSH and JSON Web Tokens throughout cybersecurity practice.

The construction was introduced by Bellare, Canetti and Krawczyk in 1996, standardized in RFC 2104 and FIPS 198-1, and is usually named after its hash, as in HMAC-SHA-256. Unlike a digital signature, an HMAC tag can be created and checked only by parties who share the same key.

How the HMAC construction works

HMAC applies the underlying hash function twice in a nested structure, using two different keys derived from the original secret. The formula is HMAC(K, m) = H((K’ XOR opad) || H((K’ XOR ipad) || m)), where K’ is the key adjusted to the hash block size, ipad is the byte 0x36 repeated, and opad is the byte 0x5C repeated.

The steps run in a fixed order. A key longer than the block size is first hashed, and a shorter key is padded with zeros to the block size. The padded key is XORed with ipad and prepended to the message for the inner hash; the inner digest is then combined with the key XORed with opad for the outer hash, whose output is the tag.

The table below shows the block and output sizes for the most common variants.

VariantBlock sizeTag lengthTypical use
HMAC-SHA-164 bytes20 bytesLegacy protocols, one-time passwords
HMAC-SHA-25664 bytes32 bytesTLS, JWT HS256, API signing
HMAC-SHA-384128 bytes48 bytesHigher-assurance TLS suites
HMAC-SHA-512128 bytes64 bytesKey derivation, 64-bit platforms
HMAC-SHA3-256136 bytes32 bytesHash diversity requirements
Common HMAC variants

Because the inner and outer keys differ, the design does not depend on the hash being collision resistant. Its security proof requires only that the compression function behaves as a pseudorandom function, which explains why HMAC-SHA-1 remains acceptable even though SHA-1 collisions are practical.

Why a plain keyed hash is not enough

A naive construction such as H(key || message) is insecure with Merkle-Damgard hashes like SHA-256 and SHA-512. These functions expose their internal state as the digest, so an attacker who sees a tag can continue hashing from that state and compute a valid tag for the original message plus appended data, without knowing the key. This is the length extension attack.

The nested outer hash in HMAC breaks this property, because the attacker never sees the inner state directly. The following table compares HMAC with simpler or alternative message authentication constructions.

ConstructionLength extension safeKey typeRemarks
H(key || message)No with SHA-2SymmetricShould never be used
H(message || key)PartlySymmetricWeak if hash collisions exist
HMACYesSymmetricProven, widely standardized
KMAC (SHA-3)YesSymmetricNative keyed mode of Keccak
Poly1305, GMACYesOne-time symmetricFast, used inside AEAD ciphers
Message authentication approaches compared

SHA-3 and BLAKE2 are not vulnerable to length extension, so they offer simpler keyed modes, yet HMAC over these functions remains valid and is often chosen for interoperability with existing libraries.

HMAC compared with digital signatures and encryption

HMAC provides integrity and origin authentication between parties sharing a key, but it does not provide confidentiality or non-repudiation. Because both parties can produce the same tag, a third party cannot tell which of them created a message, whereas a digital signature made with a private key can be attributed to its owner.

The table below separates the security goals of related primitives in the same Topic.

PrimitiveIntegrityConfidentialityNon-repudiation
Hash function aloneOnly against accidentsNoNo
HMACYes, keyedNoNo
Digital signatureYesNoYes
Symmetric encryption aloneNoYesNo
AEAD such as ChaCha20-Poly1305YesYesNo
Security properties of related primitives

When encryption and HMAC are combined manually, the recommended order is encrypt-then-MAC: the tag is computed over the ciphertext and checked before any decryption. Modern designs usually prefer an authenticated encryption mode, which provides both properties in one primitive.

Where HMAC is used in practice

HMAC appears wherever systems sharing a key must detect tampering cheaply. Its main roles fall into a few groups.

  • API request signing, where a client signs the method, path, timestamp and body so the server can reject altered or forged calls.
  • Webhook verification, where a sender signs each payload and the receiver recomputes the tag with a shared secret.
  • Token integrity, as in JSON Web Tokens using the HS256 algorithm or signed session cookies.
  • Key derivation, since HKDF and PBKDF2 are built on HMAC as a pseudorandom function.
  • One-time passwords, where HOTP and TOTP truncate an HMAC output into a short numeric code.

Choosing the variant follows a short decision process. The table below gives typical choices.

SituationRecommended choiceReason
New API or webhook designHMAC-SHA-256, 256-bit keyBroad support and ample margin
Constrained bandwidthTruncated tag of at least 128 bitsShorter tags remain secure above this size
Password storageArgon2, not raw HMACHMAC is fast and invites brute force
Compatibility with old systemsHMAC-SHA-1 if mandatedStill secure as a MAC, but plan migration
Choosing an HMAC configuration

Implementation pitfalls and limitations

Most real HMAC failures come from implementation mistakes, not from the construction. The most common is comparing tags with an ordinary string comparison that stops at the first differing byte; the timing difference lets an attacker recover a valid tag byte by byte. Tags must be checked with a constant-time comparison function.

Key quality matters as much. The key should be random and at least as long as the tag, ideally equal to the hash output length, and never a human password. Keys should be stored in a secrets manager and replaced through planned credential rotation.

Finally, HMAC alone does not prevent replay attacks. A captured message with a valid tag remains valid forever unless the signed data includes a timestamp, nonce or sequence number that the receiver checks. Ambiguous message encoding, such as concatenating fields without delimiters, can also let two different messages produce the same signed bytes, so a canonical serialization is essential.

Understanding it simply

HMAC is like a wax seal that only people with the right stamp can make. Two parties share a secret, and the sender uses it to create a short code attached to a message. The receiver uses the same secret to make the code again and compares the two.

If even one character of the message changed, the codes no longer match. A match proves the message is genuine and unchanged. It does not hide the message, though, so anyone can still read it; it only proves that nobody tampered with it on the way.

Applied in practice

An online store receives payment notifications from its payment processor through a webhook. During setup, the processor generates a random 32-byte signing secret that the store saves in its secrets manager. Every notification includes a timestamp header and an HMAC-SHA-256 tag computed over the timestamp and the raw request body.

The store’s server recomputes the tag, compares it in constant time, and rejects any message older than five minutes. One evening, an attacker sends forged notifications claiming that dozens of orders were paid. All forged requests fail verification and are logged, so no unpaid goods are shipped, and the team rotates the secret as a precaution.