HMAC Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓HMAC Implementation runs in O(n) time and O(1) space, in C# as in every other language.
- ✓System.Security.Cryptography.HMACSHA256, which derives from HMAC, KeyedHashAlgorithm and HashAlgorithm and is therefore IDisposable.
- ✓Reviewers ask for the static HashData one-shot first, and a `using var` if you genuinely need the instance.
- ✓The C# trap: Span<byte> and ReadOnlySpan<byte> are ref structs: the runtime forbids them on the heap, so they cannot be captured in a lambda or an iterator and cannot live across an await.
- ✓The static HashData path avoids allocating the managed object and its native handle, and on modern .NET it routes to the platform provider, CNG on Windows and OpenSSL elsewhere.
What HMAC Implementation actually is
HMAC Implementation in C#: what you actually reach for
C# implementation
using System;
using System.Security.Cryptography;
using System.Text;
public static class Hmac
{
public static byte[] Sign(byte[] key, string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
return HMACSHA256.HashData(key, data); // static one-shot: no object to dispose
}
// Kept synchronous on purpose: Span is a ref struct and cannot cross an await.
public static bool Verify(byte[] key, string message, ReadOnlySpan<byte> tag)
{
Span<byte> mine = stackalloc byte[32]; // SHA-256 output size
HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(message), mine);
return CryptographicOperations.FixedTimeEquals(mine, tag);
}
public static string Hex(byte[] tag) =>
Convert.ToHexString(tag).ToLowerInvariant();
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for HMAC Implementation?
System.Security.Cryptography.HMACSHA256, which derives from HMAC, KeyedHashAlgorithm and HashAlgorithm and is therefore IDisposable. The instance path is new HMACSHA256(key) then ComputeHash(byte[]) or TryComputeHash(source, destination, out written). Modern .NET also exposes static one-shot overloads, HMACSHA256.HashData(key, source) and HashData(key, source, destination), which skip the object entirely. Comparison is CryptographicOperations.FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>). Convert.ToHexString handles formatting without a per-byte loop.
What is the most common C# mistake when implementing HMAC Implementation?
Span<byte> and ReadOnlySpan<byte> are ref structs: the runtime forbids them on the heap, so they cannot be captured in a lambda or an iterator and cannot live across an await. Through C# 12 the compiler refused ref struct locals in async methods outright (CS4012), so the allocation-free stackalloc plus HashData(key, source, destination) shape could not appear in an async handler at all, and the reflex fix was to go back to the byte[] overloads. C# 13 (.NET 9) relaxed that: ref struct locals are legal in async methods now, provided they do not live across an await. The byte[] retreat quietly puts the key and the tag on the managed heap, where the GC may copy them during compaction, so CryptographicOperations.ZeroMemory on your buffer can leave an unreachable copy of the key behind. The constraint that still bites is the await boundary itself, which is why the MAC helper stays synchronous and the caller awaits around it, not inside it.
How does HMAC Implementation actually perform in C#?
The static HashData path avoids allocating the managed object and its native handle, and on modern .NET it routes to the platform provider, CNG on Windows and OpenSSL elsewhere. The instance path pays that construction plus the key schedule per object, and ComputeHash(byte[]) allocates a fresh 32-byte array on every call, which TryComputeHash into a stackalloc buffer avoids. Tiered compilation means the first calls run unoptimised tier-0 code, so a microbenchmark without warmup will badly misreport. Converting the tag to a hex string costs another allocation on top of the digest. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.