Covers HMAC-based webhook verification in ASP.NET Core: keyed integrity and authenticity, computing HMACSHA256 over the raw body, constant-time comparison, timestamp checks against replay, and secret rotation.
HMAC-SHA256 is a keyed hash: the sender computes HMAC(secret, message) and you recompute it with the same secret. A match proves the body wasn't altered and came from someone holding the secret; it does not encrypt anything.
Three details make verification correct. Hash the raw request bytes exactly as received, because re-serialising JSON changes whitespace and ordering. Compare with CryptographicOperations.FixedTimeEquals, because an early-exit comparison leaks how many leading bytes matched through timing. And sign a timestamp with the payload and reject old ones (Stripe uses a 5-minute default) so a captured request can't be replayed; store event ids for idempotency too. Keep the secret in Key Vault and accept two during rotation. Use asymmetric signatures instead when many parties must verify but shouldn't be able to forge.
"A webhook endpoint is public, so anyone can POST to it. HMAC lets me check that the request came from the provider: we share a secret, they compute HMAC-SHA256 over the payload with it and send the result in a header, and I recompute and compare. HMAC's construction, hashing the key with inner and outer pads, means you can't forge a tag without the key and avoids the length-extension problem you'd get with a naive
SHA256(secret + body).In ASP.NET Core I call
Request.EnableBuffering()and read the raw body bytes before any model binding, because the signature is over the exact bytes sent. If I let the JSON serialiser parse and re-serialise, whitespace or property order changes and valid requests fail, or worse, people 'fix' that by signing something looser. ThenHMACSHA256.HashData(secret, signedPayload)andCryptographicOperations.FixedTimeEqualsto compare. A normal==on strings stops at the first different character, and with enough requests an attacker can measure that and recover a valid signature byte by byte.Replay is the other half. A valid request captured once stays valid forever unless the signed content includes a timestamp. Stripe signs
timestamp.bodyand I reject anything older than five minutes; I also record the event id and ignore duplicates, which I need anyway because providers retry.The mistake I see is verifying the signature but then logging the whole payload with the secret header, or keeping one secret forever. I load secrets from Key Vault and accept the current and previous secret during rotation."
| Property | HMAC | Plain SHA-256 | Digital signature |
|---|---|---|---|
| Integrity | Yes | Only against accidents | Yes |
| Authenticity | Yes (shared secret) | No | Yes (private key) |
| Non-repudiation | No, both sides can create it | No | Yes |
| Confidentiality | No | No | No |
| Speed | Very fast | Very fast | Slower |
if (computedHex == Request.Headers["X-Signature"]) over JsonSerializer.Serialize(model), with no timestamp.payment.succeeded event days later, or probe signatures and measure response time.FixedTimeEquals, event-id deduplication.After adding timestamp checks and event-id deduplication to our [Stripe] endpoint, we found [about 0.3%] of deliveries were provider retries that had previously created duplicate [order confirmations]. Verification costs [under 10 microseconds] per request.
Checks whether the candidate can implement webhook verification correctly, including the subtle parts: raw body, constant-time comparison and replay.
Green flags
FixedTimeEquals and can explain timing attacksRed flags
HMAC(K, m) = H( (K' XOR opad) || H( (K' XOR ipad) || m ) )
K' = K hashed first if longer than the block size (64 bytes for SHA-256), then zero-padded to 64 bytes
ipad = 0x36 repeated 64 times, opad = 0x5c repeated 64 times
Intuitively: the key is mixed in twice with two different masks, once before hashing the message and once around the result. The outer hash is what blocks length extension: with SHA-256 (a Merkle-Damgard hash), knowing H(secret || m) lets an attacker compute H(secret || m || padding || extra) without knowing the secret, so a naive SHA256(secret + body) can be extended. With HMAC the attacker would need the key to produce the outer hash. HMAC is proven to be a secure MAC (unforgeable under chosen-message attack) as long as the hash's compression function is a PRF.
naive compare: for i in 0..n: if a[i] != b[i] return false <- time depends on i
fixed-time: diff |= a[i] ^ b[i] for all i; return diff == 0
Network jitter adds noise, but it does not remove the signal: an attacker who sends thousands of requests per candidate byte and averages the response times can still detect a few nanoseconds of difference, especially from inside the same cloud region. So constant-time comparison is required, not optional. CryptographicOperations.FixedTimeEquals loops over every byte regardless; it only returns early when lengths differ, which is not secret.
Kestrel gives you a forward-only stream. Either copy it to a buffer yourself before any binding (as in the code example), or call EnableBuffering(), which wraps it in a FileBufferingReadStream (memory up to 30 KB, then disk) so you can read and rewind. Set a request size limit; webhooks are small.
header: t=1763600000,v1=5257a8...
signed: "1763600000." + rawBody
check : |now - t| <= 300s AND HMAC matches AND eventId not seen
The timestamp must be inside the signed content, or the attacker just updates it.
Providers let you roll a secret with an overlap window. Verify against each active secret (in constant time each), log which one matched, and remove the old one when traffic on it reaches zero.
curl, then alter one character of the body.FixedTimeEquals vs SequenceEqual for equal and early-differing arrays.stripe listen --forward-to) against a local endpoint in test mode.A Minimal API webhook endpoint using a Stripe-style t=...,v1=... header, raw-body hashing, constant-time comparison, timestamp tolerance and rotation support.
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Payments.Webhooks;
public sealed record WebhookOptions
{
public required string[] Secrets { get; init; } // current + previous, from Key Vault
public TimeSpan Tolerance { get; init; } = TimeSpan.FromMinutes(5);
}
public sealed class WebhookVerifier(WebhookOptions options, TimeProvider clock)
{
public bool IsValid(string? header, ReadOnlySpan<byte> rawBody)
{
if (header is null) return false;
string? t = null, v1 = null;
foreach (var part in header.Split(','))
{
var kv = part.Split('=', 2);
if (kv is ["t", var ts]) t = ts;
else if (kv is ["v1", var sig]) v1 = sig;
}
if (t is null || v1 is null || !long.TryParse(t, NumberStyles.None, CultureInfo.InvariantCulture, out var unix))
return false;
var age = clock.GetUtcNow() - DateTimeOffset.FromUnixTimeSeconds(unix);
if (age.Duration() > options.Tolerance) return false; // replay window
byte[] expectedSig;
try { expectedSig = Convert.FromHexString(v1); } catch (FormatException) { return false; }
// Signed content = "{t}." + exact raw bytes.
byte[] prefix = Encoding.ASCII.GetBytes(t + ".");
byte[] signed = [.. prefix, .. rawBody];
foreach (var secret in options.Secrets)
{
byte[] mac = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed);
if (CryptographicOperations.FixedTimeEquals(mac, expectedSig)) return true; // constant time
}
return false;
}
}
// Program.cs
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton(sp => sp.GetRequiredService<IConfiguration>()
.GetSection("Webhooks").Get<WebhookOptions>()!);
builder.Services.AddSingleton<WebhookVerifier>();
app.MapPost("/webhooks/payments", async (HttpRequest req, WebhookVerifier verifier, CancellationToken ct) =>
{
using var ms = new MemoryStream();
await req.Body.CopyToAsync(ms, ct); // raw bytes, before any JSON parsing
byte[] body = ms.ToArray();
if (!verifier.IsValid(req.Headers["Stripe-Signature"], body))
return Results.Unauthorized(); // no detail for the caller
// Parse now, then deduplicate on event id before side effects.
return Results.Ok();
}).WithMetadata(new RequestSizeLimitAttribute(256 * 1024));
== or string.Equals. Why it is wrong: early exit leaks timing information. Instead: CryptographicOperations.FixedTimeEquals on the decoded bytes.SHA256(secret + body). Why it is wrong: vulnerable to length extension and not a standard MAC. Instead: HMACSHA256.HashData.HMAC is the right tool when exactly two parties share a secret. When you are the sender to many customers, consider asymmetric signatures (Ed25519/ECDSA with a published key) so one customer's leaked secret can't be used to forge messages to others, or per-customer secrets at minimum. Also remember the signature proves origin, not freshness or uniqueness: replay and idempotency are separate controls.
| Option | When it fits | Cost | When not |
|---|---|---|---|
| HMAC shared secret | One provider, one consumer | Secret storage and rotation | Many verifiers who must not forge |
| Per-customer HMAC secrets | You send webhooks to many tenants | Secret per tenant | When customers prefer public-key verification |
| Asymmetric signature (JWS, Ed25519) | Broadcast, public verification | Key publication, slower | Tiny internal integrations |
| mTLS | Strong channel auth between known systems | Certificate lifecycle | Public SaaS webhooks |
Track verification failures per source as a metric: a spike means a rotated secret, a clock problem or an attack.
An API key is a long random secret that identifies a calling application, not a user. It suits partner integrations, internal tools and webhooks where OAuth would be overkill, but it is a static bearer secret, so design for leaks.
RandomNumberGenerator, add a prefix and key id (sk_live_<id>_<secret>) so you can look it up and secret scanners can spot it.FixedTimeEquals.AuthenticationHandler that turns a valid key into claims; policies decide access.The trade-off: keys are simple for partners but never expire on their own; OAuth client credentials give short-lived tokens.
They answer different questions. Encoding (Base64, UTF-8, URL encoding) changes the format of data so another system can carry it; anyone can reverse it, there is no key. Encryption (AES, RSA) makes data confidential: it is reversible, but only with the key. Hashing (SHA-256) is a one-way fingerprint: same input, same fixed-size output, and you can't get the input back, so it is used for integrity checks and comparisons.
SHA256(password) is still wrong for passwords because SHA-256 is designed to be fast: a single GPU tries billions of guesses a second, and without a salt identical passwords share a hash and precomputed tables work. Passwords need a deliberately slow, salted key-derivation function such as PBKDF2, bcrypt or Argon2id. The trade-off: you spend tens of milliseconds per login so an attacker spends years per password.
Last updated 23 Nov 2026.