HMAC Signature Generator
Generate Hash-based Message Authentication Codes (HMAC-SHA256, HMAC-SHA512) for Stripe, GitHub, and API webhooks.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
Cryptographic Architecture & RFC 2104 Foundations
An HMAC (Hash-based Message Authentication Code) is a cryptographic authentication construction defined by Mihir Bellare, Ran Canetti, and Hugo Krawczyk in 1996 and formally standardized in RFC 2104 (and NIST FIPS PUB 198-1). HMAC combines a secret cryptographic key with a cryptographic hash function (such as SHA-256, SHA-512, or SHA-3) to provide simultaneous guarantees of Data Integrity (verifying payload bytes were not altered) and Authenticity (verifying the payload originated from an entity holding the shared secret key).
+---------------------------------------------------------------------------------------------------+
| THE HMAC RFC 2104 PIPELINE |
+---------------------------------------------------------------------------------------------------+
| SECRET KEY (K) MESSAGE PAYLOAD (m) |
| | | |
| [ Normalize to Block Size B ] | |
| | | |
| +--------(XOR ipad: 0x36)--------> [ (K' ⊕ ipad) || m ] |
| | | |
| | [ INNER HASH H(...) ] |
| | | |
| +--------(XOR opad: 0x5c)--------> [ (K' ⊕ opad) || InnerHash ] |
| | |
| [ OUTER HASH H(...) ] |
| | |
| v |
| HMAC AUTHENTICATION DIGEST |
+---------------------------------------------------------------------------------------------------+
The Catastrophic Flaw of Naive Hashing ($H(K \mathbin{\Vert} m)$)
A common developer mistake is attempting to build an authentication code by naively concatenating a key and a message:
- Secret Prefix Vulnerability ($H(K \mathbin{\Vert} m)$): Hash functions utilizing the Merkle-Damgård iterative compression construction (including MD5, SHA-1, and SHA-256) are fundamentally vulnerable to Length Extension Attacks. An attacker who observes $H(K \mathbin{\Vert} m)$ and the length of $m$ can calculate the hash internal state, append unauthorized payload commands ($\Delta m$), and calculate a completely valid signature $H(K \mathbin{\Vert} m \mathbin{\Vert} \text{padding} \mathbin{\Vert} \Delta m)$ without ever knowing the secret key $K$.
- Secret Suffix Vulnerability ($H(m \mathbin{\Vert} K)$): If an attacker discovers a collision between two messages such that $H(m_1) = H(m_2)$, then $H(m_1 \mathbin{\Vert} K) = H(m_2 \mathbin{\Vert} K)$, allowing the attacker to swap $m_1$ for $m_2$ undetected.
- The Nested HMAC Solution: HMAC neutralizes length extension attacks by using a two-pass nested hashing construction: hashing the message with an inner key derived from an inner padding constant (
ipad), and then hashing that intermediate digest with an outer key derived from an outer padding constant (opad).
Mathematical Construction & Block-Level Mechanics
The formal RFC 2104 specification defines HMAC as:
$$\text{HMAC}(K, m) = H\Big((K' \oplus \text{opad}) \mathbin{\Big\Vert} H\big((K' \oplus \text{ipad}) \mathbin{\Big\Vert} m\big)\Big)$$
Where:
- $H$ represents the underlying cryptographic hash function (e.g., SHA-256).
- $B$ represents the block size of the hash function (64 bytes for SHA-256; 128 bytes for SHA-512).
- $L$ represents the output digest size (32 bytes for SHA-256; 64 bytes for SHA-512).
- $\text{ipad}$ is the inner pad byte
0x36repeated $B$ times. - $\text{opad}$ is the outer pad byte
0x5crepeated $B$ times. - $\oplus$ is the bitwise exclusive-OR (XOR) operator.
- $\mathbin{\Vert}$ denotes byte concatenation.
+---------------------------------------------------------------------------------------------------+
| KEY NORMALIZATION SPECIFICATION (K') |
+---------------------------------------------------------------------------------------------------+
| Condition Action Taken Normalized Key Length |
| --------------------------------- ------------------------------- --------------------------- |
| Key length > Block size B K' = H(K) (Hash key first) Digest length L (e.g. 32 B) |
| Key length < Block size B K' = K || 0x00...00 (Zero pad) Exact Block size B (64 B) |
| Key length == Block size B K' = K (Use directly) Exact Block size B (64 B) |
+---------------------------------------------------------------------------------------------------+
Production Code Implementation
Python: Stripe/GitHub Webhook Verifier with Constant-Time Comparison
This script implements HMAC-SHA256 signature generation and constant-time webhook signature verification.
#!/usr/bin/env python3
"""
Production HMAC Engine:
Generates RFC 2104 compliant HMAC-SHA256 digests and validates incoming
Stripe/GitHub webhooks using constant-time comparison to prevent timing attacks.
"""
import hmac
import hashlib
import time
from typing import Dict, Union
class WebhookHMACService:
@staticmethod
def compute_hmac_sha256(secret_key: bytes, message_payload: bytes) -> str:
"""
Computes standard hexadecimal HMAC-SHA256 signature.
"""
mac = hmac.new(secret_key, msg=message_payload, digestmod=hashlib.sha256)
return mac.hexdigest()
@classmethod
def verify_webhook_signature(
cls,
payload_body: bytes,
signature_header: str,
webhook_secret: bytes,
tolerance_seconds: int = 300,
) -> Dict[str, Union[bool, str]]:
"""
Verifies timestamped webhook signatures (e.g., Stripe-Signature format: t=161455,v1=abc...).
Protects against replay attacks and timing-channel attacks.
"""
# Parse timestamp and signature from header
parts = dict(item.split("=") for item in signature_header.split(",") if "=" in item)
timestamp_str = parts.get("t")
expected_sig = parts.get("v1")
if not timestamp_str or not expected_sig:
return {"valid": False, "reason": "Malformed signature header format."}
try:
timestamp = int(timestamp_str)
except ValueError:
return {"valid": False, "reason": "Invalid timestamp format."}
# Check timestamp replay tolerance
current_time = int(time.time())
if abs(current_time - timestamp) > tolerance_seconds:
return {"valid": False, "reason": f"Timestamp drift exceeds {tolerance_seconds}s tolerance."}
# Construct signed payload: timestamp + "." + payload
signed_payload = f"{timestamp}.".encode("utf-8") + payload_body
computed_sig = cls.compute_hmac_sha256(webhook_secret, signed_payload)
# Constant-time comparison: Prevents side-channel timing attacks
is_authentic = hmac.compare_digest(computed_sig, expected_sig)
return {
"valid": is_authentic,
"reason": "Signature verified successfully." if is_authentic else "Cryptographic signature mismatch.",
}
# Demonstration
if __name__ == "__main__":
shared_secret = b"whsec_9938f4a8b2c1d0e9f8a7b6c5d4e3f2a1"
raw_event = b'{"event": "charge.successful", "amount_cents": 5000, "customer": "cus_9901"}'
# Simulate client sending timestamped webhook
t_now = int(time.time())
signed_data = f"{t_now}.".encode("utf-8") + raw_event
sig_hex = WebhookHMACService.compute_hmac_sha256(shared_secret, signed_data)
header_val = f"t={t_now},v1={sig_hex}"
print("--- WEBHOOK HMAC-SHA256 VERIFICATION ---")
print(f"Timestamp: {t_now}")
print(f"Signature Header: {header_val}")
# Server-side verification
audit = WebhookHMACService.verify_webhook_signature(raw_event, header_val, shared_secret)
print(f"Verification: {audit['valid']} ({audit['reason']})")
TypeScript: Microservice Webhook Verifier using Node.js crypto
import crypto from "crypto";
export interface VerificationResult {
isValid: boolean;
error?: string;
}
export class HMACSecurityValidator {
/**
* Generates a hex HMAC-SHA256 signature
*/
public static signPayload(secret: string, data: string | Buffer): string {
return crypto.createHmac("sha256", secret).update(data).digest("hex");
}
/**
* Validates payload against signature using timing-safe equal comparison
*/
public static verifySignature(
secret: string,
payload: Buffer,
receivedHexSignature: string
): VerificationResult {
const computedSignature = this.signPayload(secret, payload);
const computedBuffer = Buffer.from(computedSignature, "hex");
const receivedBuffer = Buffer.from(receivedHexSignature, "hex");
if (computedBuffer.length !== receivedBuffer.length) {
return { isValid: false, error: "Signature length mismatch." };
}
// crypto.timingSafeEqual executes in constant clock cycles
const isValid = crypto.timingSafeEqual(computedBuffer, receivedBuffer);
return {
isValid,
error: isValid ? undefined : "Cryptographic signature mismatch.",
};
}
}
Message Authentication Mechanisms Comparison Matrix
| Mechanism | Cryptographic Paradigm | Key Architecture | Performance / Throughput | Signature / Tag Size | Non-Repudiation (Third-Party Proof) |
|---|---|---|---|---|---|
| HMAC-SHA256 | Symmetric (Hash-based) | Single Shared Secret | Very Fast (~500 MB/s) | 32 Bytes (256 bits) | No (Either party can forge) |
| HMAC-SHA512 | Symmetric (Hash-based) | Single Shared Secret | Fastest on 64-bit CPUs | 64 Bytes (512 bits) | No |
| Poly1305 | Symmetric (One-Time MAC) | 32-Byte Ephemeral Key | Ultra Fast (> 2 GB/s) | 16 Bytes (128 bits) | No (Single nonce only) |
| CMAC (AES-CBC-MAC) | Symmetric (Block Cipher) | 128/256-bit AES Key | Fast with AES-NI | 16 Bytes (128 bits) | No |
| Ed25519 (EdDSA) | Asymmetric (Public Key) | Public / Private Keypair | Fast | 64 Bytes | Yes (Only private key signs) |
| RSA-PSS-2048 | Asymmetric (Public Key) | Public / Private Keypair | Slow Signing | 256 Bytes | Yes |
Catastrophic Pitfalls & Implementation Flaws
1. The Timing Attack Vulnerability on String Equality (==)
The most common security vulnerability in custom webhook verifiers is using standard string equality:
# VULNERABLE TO TIMING ATTACKS: DO NOT USE IN PRODUCTION!
if computed_signature == user_supplied_signature:
allow_access()
Standard string comparisons evaluate character by character and short-circuit upon encountering the first mismatched byte.
- An attacker measures response times over thousands of automated requests with sub-microsecond precision.
- By determining which byte guess took slightly longer to return an error, the attacker guesses the signature byte by byte, successfully forging authentication without ever knowing the secret key.
- Remediation: Always use constant-time comparison functions like Python's
hmac.compare_digest()or Node.jscrypto.timingSafeEqual().
2. Lack of Timestamp Binding (Replay Attacks)
If an HMAC is computed strictly over the message payload ($H(K \mathbin{\Vert} m)$):
- An adversary who intercepts an in-flight network request (e.g., a webhook payment confirmation for $500) can re-transmit the exact same raw payload and valid signature 100 times to the target server.
- The server will verify the signature as valid every time, potentially processing the payment 100 times.
- Remediation: Always include an explicit timestamp in the signed payload and verify that the timestamp falls within a narrow window (e.g., $\le 300$ seconds).
3. Key Reuse Across Divergent Environments
Using the identical HMAC secret key across staging, development, and production environments enables cross-environment credential leaks:
- An attacker who compromises a lower-security staging database can use the staging secret to forge valid authentication signatures on production clusters.
- Maintain unique, cryptographically random keys for each environment and tenant.