Understanding the HMAC-SHA256 generator — concept and principle
HMAC-SHA256 is a keyed message authentication code: it combines a secret key with a message to produce a 256-bit tag that only someone holding the key can create or verify. This tool computes the tag in your browser. HMAC is used to sign API requests and webhooks, to create HS256 JSON Web Tokens, and to check that cookies or messages were not altered.
How it is calculated
HMAC(K, m) = H((K′ ⊕ opad) ∥ H((K′ ⊕ ipad) ∥ m)), defined in RFC 2104.
- H is SHA-256, whose block size is 64 bytes.
- K′ is the key padded with zero bytes to 64 bytes; a key longer than 64 bytes is first hashed to 32 bytes.
- ipad is the byte 0x36 repeated 64 times, opad is 0x5c repeated 64 times, ⊕ is XOR and ∥ is concatenation.
- Key and message are taken as UTF-8 bytes, and the tag is shown as 64 hex characters.
The principle
A plain hash of key ∥ message is unsafe with SHA-256, because its Merkle–Damgård structure lets an attacker extend a message and compute a valid hash without the key (a length-extension attack). HMAC wraps the message in two nested hashes with two different derived keys; the outer hash hides the inner state, which blocks that attack. Its security is proven to rest on the pseudorandomness of the hash's compression function, so HMAC remains secure even with hashes whose collision resistance is weakened.
Worked example
- Key "secret" (6 bytes) is padded with 58 zero bytes to 64 bytes.
- Inner: XOR the padded key with 0x36, append the UTF-8 bytes of "The quick brown fox", and hash with SHA-256.
- Outer: XOR the padded key with 0x5c, append the 32-byte inner digest, and hash again.
- Result: 7a284e5025f32a846fa3e6957d10278eb5726dd4e0b04c8e0259defcd2cd0eb1.
How to read the result
The receiver recomputes the tag with the shared key and accepts the message only if the tags match exactly. Any change to the key or message, even one character or case, produces a completely different tag. Some APIs expect the tag in Base64 instead of hex; the bytes are the same.
Common mistakes
- Comparing tags with an ordinary string comparison; use a constant-time comparison to avoid timing leaks.
- Using a short, guessable key; use at least 32 random bytes for SHA-256.
- Signing a different byte form than the receiver checks (extra spaces, reordered JSON, different line endings).
Frequently asked questions
Is HMAC the same as encryption?
No. It produces a tag that proves the message is unchanged; anyone can still read the message.
What key length should I use?
RFC 2104 recommends a key at least as long as the hash output, so 32 bytes for SHA-256.
Why does my result differ from another tool?
Check the encoding of the key (text, hex or Base64), trailing newlines, and whether the output is hex or Base64.
Sources: RFC 2104, HMAC: Keyed-Hashing for Message Authentication · NIST FIPS 198-1, The Keyed-Hash Message Authentication Code (HMAC) · RFC 4231, Identifiers and Test Vectors for HMAC-SHA-224, -256, -384 and -512