📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Write code to verify an incoming webhook signed with HMAC-SHA256, for example from Stripe or GitHub. Explain what HMAC guarantees, why you must compare signatures in constant time with CryptographicOperations.FixedTimeEquals, why you must hash the raw request body, and how you prevent replay.

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.

Intermediate Coding Intermediate aspnet-core cryptography hmac security timing-attacks webhooks

🎯 Key points

  • HMAC = keyed hash: integrity plus authenticity for parties sharing a secret; resists forgery even under chosen-message attacks; no confidentiality
  • Construction: key padded to the hash block size (hashed first if longer), inner and outer pads, nested hash; blocks length extension that breaks SHA256(secret + body)
  • Compute over the exact raw bytes received, not re-serialised JSON
  • Compare with CryptographicOperations.FixedTimeEquals: timing differences are exploitable statistically even over a noisy network
  • Include a timestamp in the signed content and reject outside a tolerance (e.g. 5 minutes) to stop replay
  • Store event ids to make processing idempotent
  • Support two secrets during rotation; secrets from Key Vault
  • Return 401 without detail on failure; log the event server-side

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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. Then HMACSHA256.HashData(secret, signedPayload) and CryptographicOperations.FixedTimeEquals to 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.body and 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."


What HMAC gives you

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

The vulnerable code, the attack and the fix

  • Vulnerable: if (computedHex == Request.Headers["X-Signature"]) over JsonSerializer.Serialize(model), with no timestamp.
  • Attack in one line: replay a captured payment.succeeded event days later, or probe signatures and measure response time.
  • Fixed: raw body, signed timestamp with tolerance, FixedTimeEquals, event-id deduplication.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can implement webhook verification correctly, including the subtle parts: raw body, constant-time comparison and replay.

Green flags

  • Hashes the raw body and explains why
  • Uses FixedTimeEquals and can explain timing attacks
  • Adds a signed timestamp and event-id deduplication
  • Mentions secret rotation and Key Vault

Red flags

  • String comparison of hex signatures
  • Thinks HMAC encrypts the payload
  • No replay protection

📚 Learn in depth

1. HMAC construction

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.

2. Timing attacks

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.

3. Reading the raw body in ASP.NET Core

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.

4. Replay protection

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.

5. Secret rotation

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.

Try it yourself

  1. Implement the endpoint below and send a request with curl, then alter one character of the body.
  2. Sign the payload after pretty-printing the JSON and see verification fail.
  3. Replay a valid request after 6 minutes and confirm it is rejected.
  4. Benchmark FixedTimeEquals vs SequenceEqual for equal and early-differing arrays.
  5. Use the Stripe CLI (stripe listen --forward-to) against a local endpoint in test mode.

💻 Code

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));

⚠ Common mistakes

  • Mistake: Comparing signatures with == or string.Equals. Why it is wrong: early exit leaks timing information. Instead: CryptographicOperations.FixedTimeEquals on the decoded bytes.
  • Mistake: Hashing the model after JSON deserialisation. Why it is wrong: re-serialisation changes bytes, so valid requests fail or verification gets loosened. Instead: hash the raw request body.
  • Mistake: No timestamp or tolerance check. Why it is wrong: captured requests can be replayed indefinitely. Instead: sign the timestamp and reject outside a short window.
  • Mistake: SHA256(secret + body). Why it is wrong: vulnerable to length extension and not a standard MAC. Instead: HMACSHA256.HashData.
  • Mistake: Processing the event without deduplication. Why it is wrong: providers retry, causing duplicate side effects. Instead: store processed event ids with a unique constraint.
  • Mistake: Secrets in appsettings.json and never rotated. Why it is wrong: leaks are permanent. Instead: Key Vault, two active secrets during rotation.
  • Mistake: Returning detailed reasons ("timestamp too old", "bad signature"). Why it is wrong: helps attackers probe. Instead: a generic 401 and detailed server-side logs.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares webhook secrets with API keys. Why: Checks how API keys are stored, scoped and rotated, and when they are appropriate.
    How to answer

    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.

    • Generate 256 random bits with RandomNumberGenerator, add a prefix and key id (sk_live_<id>_<secret>) so you can look it up and secret scanners can spot it.
    • Store only a hash (SHA-256 is fine for high-entropy keys), show the key once, and compare with FixedTimeEquals.
    • Scope each key, set an expiry, allow two active keys for rotation, track last use.
    • Implement an 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.

  2. When: Candidate explains HMAC as a keyed hash. Why: Checks the distinction between hashing, encryption and encoding.
    How to answer

    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.

↩ Usually asked after

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me