Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

Why does HMAC use a key and hash twice?

Suppose two services exchange a message saying “Order 42 has shipped.” With a plain SHA-256 digest, anyone can create a replacement message and compute its digest. HMAC uses an existing hash function to produce an authentication tag tied to the message and to a secret key that the services share. Only a key holder can reliably generate a valid tag. The recipient computes the tag independently and compares it with the one received. RFC 2104

HMAC-SHA-256: create and verify a tag
  1. Prepare the shared keyIf the key is longer than 64 bytes, hash it. Pad the resulting key with zeros to 64 bytes if needed. Call this block K.
  2. Sender · Inner hashXOR each byte of K with 0x36. Append the message and hash with SHA-256 to get the 32-byte inner digest.
  3. Sender · Outer hashXOR each byte of K with 0x5c. Append the inner digest and hash with SHA-256. Send the message and this 32-byte tag.
  4. Recipient · VerifyRepeat inner then outer hash with K and the received message. Compare all 32 tag bytes in constant time; accept only on a match.

The inner hash reads the message and the outer hash wraps the result

  1. Bring the secret key to the SHA-256 block size of 64 bytes. If it is longer than a block, first hash it with SHA-256. Pad any shorter value with trailing zeros. Call the resulting block K.
  2. XOR each byte of K with 0x36, append the message, and hash the result with SHA-256. For a long message, you can process it in chunks as it arrives to compute the inner digest.
  3. XOR each byte of K with 0x5c, append the 32-byte inner digest, and hash the result again with SHA-256. Send this outer digest as the tag.

The two constants give the inner and outer hashes different starting blocks derived from the same key. Regardless of the message length, the outer hash receives a key-derived block followed by a fixed-length digest. A length-extension calculation that treats the public tag as a SHA-256 intermediate state produces a hash of a different input form. A valid HMAC for the extended message requires a new inner digest under the key. SHA-256 internal state · RFC 2104 §2

Who can verify the tag?

If the received message says “Order 43,” the recipient’s inner hash processes a different order number, and the tag check fails. The recipient holds the same key and can also create valid messages. Giving the key to more people lets more people verify tags and also lets them create tags. Use a digital signature when you want people to verify something you distribute using a public key. In the QuantAegis Rust API, HmacSha256::verify checks the tag. Using HMAC · Digital signature example