Calculate keyed-hash message authentication codes (HMAC) to verify integrity.
HMAC (Hash-based Message Authentication Code) is a specific construction for calculating a message authentication code involving a cryptographic hash function (like SHA-256) in combination with a secret cryptographic key.
It simultaneously verifies both the data integrity (the message hasn't been altered) and the authenticity (the message comes from someone who knows the secret key).
A naive approach to authentication is appending the secret to the message and hashing it (e.g., SHA-256(secret || message)). However, this is critically vulnerable to Length Extension Attacks.
An attacker who intercepts the hash and the original message can append extra data and compute a valid hash for the new message without ever knowing the secret.
HMAC solves this by hashing the secret twice in a nested structure: H(Key XOR opad, H(Key XOR ipad, message)), rendering length extension mathematically impossible.
X-Hub-Signature). Your server recalculates the HMAC using the payload and your shared secret, comparing it to the header to prove Stripe sent it.When verifying an HMAC, if you use standard string equality (if (received_hmac === calculated_hmac)), the comparison fails immediately upon the first mismatched character. An attacker can measure this microsecond difference to guess the HMAC character by character (a Timing Attack).
Fix: Always use a constant-time comparison function (like crypto.subtle.verify or Node's crypto.timingSafeEqual) which takes the exact same amount of time regardless of where the mismatch occurs.
What security vulnerability does HMAC specifically protect against that naive hashing (hash(secret + message)) does not?