HMAC-SHA256 vs SHA-256: Why Webhooks Reject Plain Hashes
Plain SHA-256 checks data integrity, not who sent it. Learn why SHA-256(secret + body) allows length-extension forgery and how to verify HMAC webhooks safely.
A plain SHA-256 hash proves that a file or payload hasn’t been corrupted in transit. It does not prove who created that payload, because anyone can compute a valid SHA-256 digest for any message.
HMAC-SHA256 (Hash-based Message Authentication Code) mixes a shared secret key into two nested SHA-256 passes. That gives you both integrity and authenticity: only someone holding the secret can produce a matching webhook signature.
If you need to test a webhook payload and signing secret locally without pasting credentials into a remote server, try our browser-only hash and HMAC generator.
Why SHA-256(secret + body) is still vulnerable
Many developers try to skip HMAC and simply hash the secret right before the request body (sha256(secret + body)). That looks safe, yet it fails against length-extension attacks.
SHA-256 processes data in 64-byte blocks using the Merkle-Damgard construction. The final 32-byte digest is the algorithm’s complete internal state at the end of the last block.
Because that internal state is exposed in the signature header, an attacker who knows the message length can resume hashing from the digest and append extra data (such as &role=admin) without ever knowing your secret key.
HMAC fixes this with two nested passes defined in RFC 2104:
HMAC(K, m) = SHA256( (K' XOR opad) || SHA256( (K' XOR ipad) || m ) )
The inner hash runs over the key XORed with 0x36 (ipad) plus your message. The outer hash seals that inner digest with the key XORed with 0x5c (opad), hiding the internal state completely so nobody can extend it.

| Feature | Plain SHA-256 |
Naive SHA-256(key + body) |
HMAC-SHA256 |
|---|---|---|---|
| Needs a secret key? | No | Yes | Yes |
| Proves sender identity? | No | Broken | Yes |
| Resists length-extension? | N/A | No | Yes |
| Best use case | File checksums, ETags | Never use | Webhooks, API request signing |
For a closer look at when plain hashes are the right tool (like verifying software downloads), read our comparison of MD5 vs SHA-256 checksums.
Why webhook HMAC verification fails in production
Even when teams switch to HMAC-SHA256, two everyday implementation bugs cause valid webhooks to fail or stay insecure:
1. Hashing parsed JSON instead of raw bytes
Frameworks like Express, FastAPI, and Django parse JSON bodies into objects before your route runs. If you call JSON.stringify(req.body) to rebuild the payload, a single added space changes the signature completely.
Take the secret whsec_demo_9f2a and a compact Stripe-style payload:
- Raw body (
{"event":"invoice.paid","amount":4900}):9f3c61356951fa02649ff75a098a312f3cd9af2b2d1205b146e762a643e83ac6 - Re-serialized (
{"event": "invoice.paid", "amount": 4900}):eb7570aed86457528a216c0d0b76a540db993002acfefcb6cbc8038a6f69aa58
Always read the exact raw UTF-8 byte buffer before any JSON parser touches it.
2. Comparing signatures with === instead of constant-time functions
Standard string comparison stops at the first mismatched byte. Under enough requests, microsecond timing differences leak how many leading hex characters matched.
Use crypto.timingSafeEqual() in Node.js (always check buffer lengths first so it doesn’t throw RangeError) or hmac.compare_digest() in Python.
Safe HMAC-SHA256 verification in Node.js and Python
Node.js (Express raw body)
import crypto from "node:crypto";
import express from "express";
const app = express();
// Capture exact raw bytes on the webhook route before express.json()
app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => {
const sigHeader = req.get("x-hub-signature-256") || "";
const providedHex = sigHeader.replace(/^sha256=/, "").trim().toLowerCase();
const expectedHex = crypto
.createHmac("sha256", process.env.WEBHOOK_SECRET)
.update(req.body) // Buffer of raw UTF-8 bytes
.digest("hex");
const provided = Buffer.from(providedHex, "hex");
const expected = Buffer.from(expectedHex, "hex");
if (provided.length !== expected.length || !crypto.timingSafeEqual(provided, expected)) {
return res.status(401).send("Invalid signature");
}
const event = JSON.parse(req.body.toString("utf8"));
res.status(200).json({ received: event.event });
});
Python (Flask, FastAPI, or Django)
import hashlib
import hmac
def verify_webhook(raw_body: bytes, secret: str, signature_header: str) -> bool:
expected = hmac.new(
secret.encode("utf-8"),
raw_body,
hashlib.sha256,
).hexdigest()
provided = signature_header.removeprefix("sha256=").strip().lower()
return hmac.compare_digest(expected, provided)
Notice that HMAC-SHA256 is also the exact algorithm behind HS256 JSON Web Tokens. If you verify JWT signatures in the same backend, check our guide on fixing the JWT alg:none vulnerability.
HMAC-SHA256 FAQ
Does HMAC-SHA256 encrypt my webhook payload?
No. HMAC only creates a 32-byte authentication tag (64 hex characters). The JSON body stays readable in plaintext, so you still need HTTPS (TLS) for confidentiality.
Should I use HMAC-SHA256 to hash user passwords?
No. HMAC-SHA256 is designed to run fast, which makes offline brute-force guessing easy if your database leaks. Use Argon2id, scrypt, or bcrypt for passwords.
Why did crypto.timingSafeEqual throw RangeError?
timingSafeEqual requires both Buffer arguments to have the exact same byte length. If a header is missing, truncated, or contains non-hex characters, check provided.length === expected.length before calling it.
Debug webhook digests and verify hex or Base64 signatures client-side with the ToolQuilt hash and HMAC generator.