$devtoolkit.sh/glossary/what-is-hmac

What is HMAC? — Hash-Based Message Authentication Explained

Definition

HMAC (Hash-Based Message Authentication Code) is a technique for verifying both the integrity and authenticity of a message using a cryptographic hash function combined with a secret key. Unlike a plain hash, which anyone can compute, an HMAC can only be verified by someone who possesses the secret key. This makes HMAC suitable for authenticating API requests, signing webhook payloads, and producing the signature in JWT tokens.

How It Works

HMAC works by combining the secret key with the message in a specific mathematical way before hashing. The standard construction is HMAC(key, message) = H((key XOR opad) || H((key XOR ipad) || message)), where H is the underlying hash function (like SHA-256) and ipad/opad are fixed padding constants. The result is a fixed-length authentication tag. A receiver who knows the secret key can recompute the HMAC and compare it to the one sent with the message — if they match, the message is authentic and unmodified.

Common Use Cases

  • Signing JWT tokens with HS256 (HMAC-SHA256) for API authentication
  • Authenticating webhook payloads (GitHub, Stripe, Slack all use HMAC-SHA256)
  • Computing request signatures for AWS API authentication (SigV4)
  • Generating time-based one-time passwords (TOTP) in two-factor authentication
  • Verifying API request integrity in REST API authentication schemes

Example

HMAC-SHA256
Key: "my-secret-key"
Message: "{"user":"alice","amount":100}"

Signature: a4b9c8d7e6f5... (32-byte hex string)

Webhook header:
X-Hub-Signature-256: sha256=a4b9c8d7e6f5...

Related Tools

FAQ

What is the difference between HMAC and a digital signature?
HMAC uses a symmetric secret key — both sender and receiver need the same key, making it suitable for private API authentication. A digital signature (RSA, ECDSA) uses an asymmetric key pair: only the holder of the private key can sign, but anyone with the public key can verify.
Which hash function should I use with HMAC?
HMAC-SHA256 is the standard choice for new systems — it provides 128 bits of security with a 32-byte output. HMAC-SHA512 gives more security but is slower. Avoid HMAC-MD5 for security-critical uses because MD5 has known weaknesses, though the HMAC construction does make MD5 stronger than plain MD5.
How do I verify a webhook signature?
To verify a webhook from services like GitHub or Stripe: 1) Extract the signature from the X-Hub-Signature-256 or Stripe-Signature header. 2) Compute HMAC-SHA256 of the raw request body using your webhook secret as the key. 3) Compare using a constant-time comparison function to prevent timing attacks.

Related Terms

/glossary/what-is-hmacv1.0.0