How HMAC-SHA256 is built
HMAC wraps a normal hash function around the key twice. The key is first padded to the block size of the hash (64 bytes for SHA-256; longer keys are hashed down first). It is mixed with one constant to make an inner key and with another to make an outer key. The result is H(outer key + H(inner key + message)). This two-step design is why an HMAC is safe even with hashes such as SHA-256 that would be open to length-extension attacks if you simply hashed key + message.
Check your setup with a known answer
RFC 4231 publishes test values for HMAC-SHA256. With the key Jefe and the message what do ya want for nothing? the hex result must be:
5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
If your code gives anything else for this input, the problem is in your code (often the key and message are swapped, or a newline sneaked in), not in the webhook provider.
Verify a webhook signature in Node.js and Python
// Node.js
const crypto = require('crypto')
const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex')
const ok = expected.length === received.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))
# Python
import hmac, hashlib
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
ok = hmac.compare_digest(expected, received)
rawBody must be the bytes exactly as they arrived. In Express, read it with express.raw() on the webhook route; in Flask, use request.get_data().
Where providers put the signature
- GitHub: X-Hub-Signature-256 header, hex HMAC-SHA256 of the body, prefixed with sha256=.
- Shopify: X-Shopify-Hmac-Sha256 header, Base64 HMAC-SHA256 of the body.
- Slack: X-Slack-Signature, v0= plus the hex HMAC-SHA256 of v0:timestamp:body, with the timestamp in X-Slack-Request-Timestamp.
- Stripe: Stripe-Signature, with t= and v1= values as described in the questions above.
Strip the prefix (sha256= or v0=) before comparing, and decode Base64 only when the provider uses it.