Production-Safe HMAC Authentication and Verification in C#
Authenticate message integrity with HMAC-SHA-256.
How to authenticate messages with HMAC-SHA256 in C#, such as webhooks: what a valid tag proves, how to verify one safely, which bytes to sign, key rotation and replays.
At a glance
- HMAC combines a hash with a shared secret key: without the key, nobody can make a valid tag for a changed message.
- It proves integrity and that some key holder made the message. It does not hide the message, and it gives no non-repudiation: every verifier can also create tags.
- Compare tags with
CryptographicOperations.FixedTimeEquals, never with==orSequenceEqual. - Sign exact bytes: both sides must agree on the encoding, field order and format; when the protocol signs the raw body, verify it before parsing.
- HMAC does not stop replays. A signed timestamp limits a message's age; a stored nonce or message ID rejects a second use.
What a valid tag proves
| Tool | Key | Proves | Who can create it |
|---|---|---|---|
| SHA-256 digest | none | accidental change, only if the digest itself is protected | anyone |
| HMAC-SHA256 | one shared secret | integrity, and that a key holder made it | every key holder |
| digital signature (RSA, ECDSA) | a private key signs, the public key verifies | integrity, and which private key signed it | anyone with access to the private key |
| authenticated encryption (AES-GCM) | one shared secret | confidentiality and integrity | every key holder |
An attacker who can change a message can recompute its plain hash. An HMAC needs the key.
Verify a tag
using System.Security.Cryptography;
using System.Text;
byte[] key = RandomNumberGenerator.GetBytes(32); // in production: from a secret store
byte[] otherKey = RandomNumberGenerator.GetBytes(32);
byte[] message = Encoding.UTF8.GetBytes("orderId=123&amount=49.95¤cy=USD");
byte[] tag = HMACSHA256.HashData(key, message); // .NET 6: one call, no object
Console.WriteLine($"tag length: {tag.Length} bytes");
Console.WriteLine($"same message: {Verify(key, message, tag)}");
Console.WriteLine($"amount changed: {Verify(key, Encoding.UTF8.GetBytes("orderId=123&amount=99.95¤cy=USD"), tag)}");
Console.WriteLine($"other key: {Verify(otherKey, message, tag)}");
Console.WriteLine($"same message again, a replay: {Verify(key, message, tag)}");
static bool Verify(byte[] key, byte[] message, byte[] suppliedTag) =>
suppliedTag.Length == HMACSHA256.HashSizeInBytes
&& CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(key, message), suppliedTag);tag length: 32 bytes same message: True amount changed: False other key: False same message again, a replay: True
- Recompute the tag over the bytes you received and compare it with the supplied one. A changed byte or a different key fails.
- Decode the supplied tag strictly (hex or Base64, as the protocol says) and reject a wrong length before comparing;
HashSizeInBytes(.NET 7) is 32. - The replay passes: verification keeps no state, so freshness needs its own check.
FixedTimeEqualstakes the same time however many bytes match, so an attacker cannot learn the tag byte by byte from response times.
Which bytes to sign
- Verify exactly the bytes and fields the sender's protocol signs. When it signs the raw body, keep the body as received, before any parsing or re-serializing: JSON written again can differ in spacing, order or number format.
- For several fields, define one canonical form: UTF-8, a fixed field order, and explicit framing such as a length prefix for each field. Plain concatenation is ambiguous:
"ab" + "c"and"a" + "bc"give the same bytes. - Include everything an attacker could swap: the timestamp, a nonce or message ID, the method, the path, the sender and the key ID, besides the body.
- Limit the body's size before reading it, and act on the message only after the tag checks out.
Keys and rotation
- Generate keys with
RandomNumberGenerator.GetBytes. A key can be any length; keys longer than 64 bytes are hashed first, and .NET's documentation recommends 64 bytes. - Keep keys in a secret store (such as Azure Key Vault), never in source code, logs or browsers. Use a separate key for each purpose, sender or tenant.
- When you control the protocol, send a key ID with each message. Sign with the current key; during a rotation, also accept the previous key for a short, fixed overlap. Choose the key by its ID; without an ID, check only the current and the previous key, never every key you have.
- Retire a leaked key at once, and watch whether the old key is still being used.
Replays
- A signed timestamp limits the window: reject one that is too old (for example over 5 minutes) or too far in the future, with a small allowance for clock skew.
- Inside that window, a copy is still valid. To accept a message once, store its nonce or ID with a unique constraint after the tag check, and keep it until the message could no longer be accepted (the age limit plus the skew).
- When the replay store is down, reject the message or ask for a retry instead of skipping the check.
Common mistakes
- An unkeyed SHA-256 digest used as authentication: use HMAC with a secret key.
- Comparing tags with
==,SequenceEqualor as strings: decode, check the length, and useFixedTimeEquals. - Signing the parsed object while the sender signed the raw bytes: verify the exact bytes received.
- Signing the body only: include the timestamp, nonce, method, path and key ID.
- One key for every partner and purpose: use separate keys, with an ID for rotation.
- Treating a valid tag as proof of freshness: check the age and store nonces.
In an interview
Why not send a SHA-256 hash of the message? Anyone who can change the message can recompute the hash. An HMAC also needs the secret key, so a changed message cannot get a valid tag.
HMAC or a digital signature? HMAC is faster and uses one shared key, so every verifier could also have signed: no non-repudiation. A signature (RSA, ECDSA) uses a private key to sign and a public key to verify, so it proves which key signed and lets anyone verify.
Why FixedTimeEquals? A normal comparison stops at the first different byte, so its timing can reveal how much of a guessed tag is right. FixedTimeEquals takes the same time for equal-length inputs.
Does a valid HMAC stop replay attacks? No. The same message and tag verify again and again. Sign a timestamp to limit the age, and store a nonce or message ID to reject a second use within that window.
How do you rotate an HMAC key without downtime? Put a key ID in each message (without one, try only the current and the previous key). Sign with the new key, accept the old one for a short, fixed overlap, then retire it.
What exactly do you sign for a webhook? Exactly what the sender's protocol specifies, often the raw body bytes plus a timestamp and a delivery ID. Keep the raw body and verify it before parsing the JSON.
Check yourself
A service verifies the same message and tag twice with the right key. What happens?
Show answer
Correct answer: B
HMAC verification recomputes the tag and keeps no state, so a copy verifies again; stopping replays needs a stored nonce or ID.
Option A: Nothing records the first check, so nothing can fail the second.
Option C: The HMAC methods have no notion of a message already seen.
Option D: A nonce matters only if the protocol includes and stores it; the tag itself still verifies.
Why is CryptographicOperations.FixedTimeEquals used to compare tags?
Show answer
Correct answer: B
An early-exit comparison takes longer the more leading bytes match, which leaks the tag; FixedTimeEquals compares every byte of equal-length inputs.
Option A: Speed is not the point; constant timing is.
Option C: It only compares two byte spans.
Option D: It takes bytes; decode the supplied tag before comparing.
Who can create a valid HMAC tag for a message?
Show answer
Correct answer: C
HMAC is symmetric: the same key creates and checks tags, so every key holder, the verifier included, can create one.
Option A: The receiver holds the same key, so the tag cannot prove which holder made it.
Option B: HMAC has no public key; that is a digital signature.
Option D: Reading the message is not enough; the tag needs the key.
Sources
- HMACSHA256.HashData: the one-call HMAC.
- HMACSHA256 constructor: key length, keys over 64 bytes hashed, the recommended size.
- CryptographicOperations.FixedTimeEquals: a comparison whose time does not depend on the content.
- RandomNumberGenerator.GetBytes: random key bytes.
- Cryptographic services: hashes, MACs, signatures and encryption compared.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·