HMAC-SHA256 Explained

Learn how HMAC-SHA256 combines a secret key with the SHA-256 hash function to produce tamper-proof message authentication codes for secure data verification.

HMAC Basics

Detailed Explanation

What Is HMAC-SHA256?

HMAC-SHA256 is a specific type of message authentication code (MAC) that combines a secret key with the SHA-256 hash function. The acronym stands for Hash-based Message Authentication Code using SHA-256 as the underlying hash algorithm. It produces a 256-bit (32-byte) authentication tag, typically represented as a 64-character hexadecimal string.

How HMAC-SHA256 Works Internally

The HMAC construction, defined in RFC 2104, uses two rounds of hashing with a secret key. The process works as follows:

  1. If the key is longer than the hash block size (64 bytes for SHA-256), it is first hashed with SHA-256 to produce a 32-byte key.
  2. The key is padded to the block size and XORed with an inner padding constant (0x36 repeated).
  3. The message is appended to this inner-padded key, and the result is hashed with SHA-256 to produce an intermediate hash.
  4. The key is then XORed with an outer padding constant (0x5c repeated).
  5. The intermediate hash is appended to this outer-padded key, and the result is hashed again with SHA-256.

The formula is: HMAC(K, m) = H((K' XOR opad) || H((K' XOR ipad) || m))

Why Two Rounds of Hashing?

The double-hashing design prevents length extension attacks that affect plain hash-based MACs. If you simply concatenate a key with a message and hash it (SHA256(key || message)), an attacker who knows the hash output can append additional data and compute a valid hash without knowing the key. HMAC's nested structure eliminates this vulnerability entirely.

Output Properties

HMAC-SHA256 always produces exactly 256 bits regardless of input size. Changing a single bit in either the key or the message produces a completely different output. Without the secret key, it is computationally infeasible to forge a valid HMAC, even if the attacker knows the message and the resulting tag.

Use Case

HMAC-SHA256 is the most widely used HMAC variant, securing API authentication, webhook signature verification, JWT signing (HS256), and session token generation across virtually every major web platform.

Try It — HMAC Generator

Open full tool