Skip to content
iamnoobs

Developer Tutorials

What Is HMAC? Hash-Based Message Authentication Codes Explained

Understand how HMAC works, why hashing alone is not enough for message authentication, and how HMAC protects integrity and authenticity.

By iamnoobs

What Is HMAC? Hash-Based Message Authentication Codes Explained

An HMAC (Hash-based Message Authentication Code) is a specific type of message authentication code that combines a cryptographic hash function (such as SHA-256 or SHA-512) with a secret key. It allows two communicating parties to verify both the integrity (that the message was not altered) and the authenticity (that the message came from someone who holds the secret key) of a payload.

For example, a hex-encoded HMAC-SHA256 signature generated for a payload looks like this:

a35fbc90e4f13d80a37f52f829033320c1ec248a31e3d06e2324e93435b0b2e8

Unlike a standard cryptographic hash (like SHA-256), which can be computed by anyone who has the input message, an HMAC requires a shared secret key. Without the key, an attacker cannot generate a valid HMAC signature for a modified message.

In this guide, you'll learn what HMAC is, why standard hashing is insufficient for authentication, how the HMAC algorithm works internally, common real-world use cases (like Webhook signatures and API authentication), and how to generate HMAC digests using the IamNoobs Cryptographic Hash Generator.

Why Plain Hashing Is Not Enough

To understand HMAC, it helps to understand why standard hash functions alone cannot prove message authenticity.

A standard cryptographic hash function (such as SHA-256) takes an arbitrary input string and returns a fixed-length string of bytes. It is deterministic and publicly known:

$$\text{Hash} = H(\text{Message})$$

The Length-Extension and Tampering Problem

Suppose an API sender wants to send a payload to a receiver and verify that it wasn't modified in transit. If the sender simply computes a hash of the payload:

  1. Sender transmits: {"amount": 100} and hash = SHA256('{"amount": 100}').
  2. An attacker intercepts the transmission and modifies the payload to {"amount": 10000}.
  3. The attacker recomputes hash_new = SHA256('{"amount": 10000}') and replaces the original hash.
  4. The receiver receives the modified payload and hash, computes the SHA-256 of the payload, finds that it matches hash_new, and assumes the message is valid.

Even if you append a secret key directly to the data before hashing (e.g., $H(\text{Key} \mathbin{\Vert} \text{Message})$), certain hashing algorithms (like MD5, SHA-1, and SHA-256) are vulnerable to length-extension attacks, where an attacker can append data to the message and compute a valid hash without knowing the secret key.

HMAC solves this problem by wrapping the secret key and the hash function in a multi-pass structure defined by RFC 2104.

How HMAC Works

HMAC uses a two-pass hash calculation that incorporates a secret key alongside internal and external padding constants.

The HMAC Formula

The mathematical definition of HMAC for a message $M$ and secret key $K$ using a cryptographic hash function $H$ is:

$$\text{HMAC}(K, M) = H\Big((K \oplus \text{opad}) \mathbin{\Vert} H\big((K \oplus \text{ipad}) \mathbin{\Vert} M\big)\Big)$$

Where:

  • $H$: A cryptographic hash function (e.g., SHA-256, SHA-512).
  • $K$: The shared secret key. (If $K$ is longer than the block size of $H$, it is hashed first; if shorter, it is padded with zeros).
  • $\text{ipad}$: Inner padding byte (0x36 repeated to match the block size).
  • $\text{opad}$: Outer padding byte (0x5c repeated to match the block size).
  • $\oplus$: Bitwise XOR operation.
  • $\mathbin{\Vert}$: String concatenation.

Step-by-Step Breakdown

  1. Key Normalization: If the secret key is longer than the hash function's block size (64 bytes for SHA-256), hash the key. If it is shorter, pad it with zero bytes up to the block size.
  2. Inner Pass: XOR the normalized key with $\text{ipad}$ (0x36). Concatenate the message $M$ to this value and compute the inner hash.
  3. Outer Pass: XOR the normalized key with $\text{opad}$ (0x5c). Concatenate the result of the inner hash to this value and compute the final outer hash.
  4. Final Output: The resulting digest is the HMAC signature.

Because the key is mixed twice with different padding vectors, length-extension attacks are mathematically impossible against HMAC.

Common Uses for HMAC

HMAC is a core component of modern web and application security protocols.

1. Webhook Verification (Stripe, GitHub, Shopify)

When third-party services send webhooks (HTTP POST notifications) to your server, your application needs to verify that the request actually came from the platform and not an impersonator.

Services typically pass an HMAC signature in an HTTP header (e.g., X-Hub-Signature-256 or Stripe-Signature):

  1. The platform generates an HMAC of the HTTP request body using your shared API secret.
  2. The platform sends the HTTP POST request with the HMAC signature in the header.
  3. Your server receives the request, computes the HMAC locally using your secret, and compares it to the incoming header signature using a constant-time string comparison.

2. AWS Signature Version 4 (AWS API Requests)

Amazon Web Services (AWS) uses nested HMAC-SHA256 calculations to sign REST API requests. Rather than sending your AWS Secret Access Key over the network, AWS requires your client to generate a signed authorization header computed via HMAC using your secret key, the request date, region, and target service name.

3. JWT Signatures (HS256)

JSON Web Tokens (JWTs) using the HS256 signing algorithm utilize HMAC-SHA256 to ensure token integrity:

HMAC-SHA256(base64Url(header) + "." + base64Url(payload), secret)

This guarantees that clients cannot alter claims inside the JWT (such as changing user_id or role) without invalidating the signature.

4. One-Time Passwords (HOTP / TOTP)

Two-factor authentication (2FA) apps like Google Authenticator use TOTP (Time-Based One-Time Password, defined in RFC 6238), which is built on HOTP (RFC 4226). HOTP computes an HMAC-SHA1 signature using a shared secret key and a moving counter or current time step, then truncates the result into a 6-digit passcode.

HMAC vs. Digital Signatures vs. Encryption

Feature Plain Hash (e.g., SHA-256) HMAC Digital Signatures (e.g., RSA / ECDSA) Encryption (e.g., AES)
Primary Purpose Data integrity check Integrity + Authentication Integrity + Authentication + Non-repudiation Confidentiality
Requires Key No Yes (Symmetric / Shared) Yes (Asymmetric: Private key signs, Public key verifies) Yes (Symmetric or Asymmetric)
Reversible No No No Yes (with decryption key)
Hides Payload Data No No No Yes

Generating HMAC Hashes with IamNoobs

The IamNoobs Cryptographic Hash Generator allows you to calculate cryptographic hashes and HMAC digests locally inside your web browser using WebCrypto APIs.

How to calculate an HMAC digest

  1. Open the IamNoobs Cryptographic Hash Generator.
  2. Select your desired algorithm (e.g., SHA-256 or SHA-512).
  3. Enter your secret key in the key field.
  4. Enter or paste your payload into the message input field.
  5. View the resulting hex-encoded HMAC output instantly.

Expected output format:

a35fbc90e4f13d80a37f52f829033320c1ec248a31e3d06e2324e93435b0b2e8

Important Security Best Practices

  • Use Constant-Time Comparison: When checking incoming HMAC signatures in code (e.g., validating webhooks), always use timing-safe comparison functions (like crypto.timingSafeEqual() in Node.js or hmac.compare_digest() in Python) to prevent timing side-channel attacks.
  • Keep Secret Keys Secure: Never expose secret keys in public client-side JavaScript code or public GitHub repositories.
  • Use Modern Hash Functions: Prefer HMAC-SHA256 or HMAC-SHA512 over legacy variants like HMAC-MD5 or HMAC-SHA1.

Frequently Asked Questions

1. What does HMAC stand for?

HMAC stands for Hash-based Message Authentication Code. It is a construction for calculating message authentication codes using a cryptographic hash function in combination with a secret key.

2. Is HMAC a form of encryption?

No. HMAC provides integrity and authenticity, not confidentiality. Anyone with access to the message can read it; the HMAC signature simply proves that the message has not been altered and came from a holder of the secret key.

3. Can you reverse or decrypt an HMAC?

No. HMAC is a one-way cryptographic hash function construction and cannot be decrypted or reversed to recover the secret key or original message.

4. What is the difference between SHA-256 and HMAC-SHA256?

SHA-256 is a standard cryptographic hash function that takes a message and outputs a fixed-size digest. HMAC-SHA256 combines the SHA-256 algorithm with a secret key in a secure two-pass process to authenticate both the sender and the message contents.

5. Why shouldn't I use standard == string comparison to verify HMACs?

Standard string comparison operators stop checking as soon as they encounter the first mismatched character. This introduces timing variations that an attacker can exploit via a timing attack to guess the signature byte by byte. Always use constant-time string comparison functions.

6. Which hash function should I use with HMAC?

HMAC-SHA256 and HMAC-SHA512 are currently recommended for general software engineering and API security.

Conclusion

HMAC is a fundamental building block of modern web security. By combining cryptographic hash functions with shared secret keys, HMAC enables systems to verify that messages are authentic and unaltered without requiring complex public-key infrastructure.