Comparing license tokens without a timing leak
Here is a comparison that looks obviously correct and is quietly a security hole: static bool TokenMatches(byte[] presented, byte[] expected) { if (presented.Length != expected.Length) return false; for (int i
Here is a comparison that looks obviously correct and is quietly a security hole:
static bool TokenMatches(byte[] presented, byte[] expected)
{
if (presented.Length != expected.Length) return false;
for (int i = 0; i < expected.Length; i++)
if (presented[i] != expected[i]) return false;
return true;
}
It returns the right answer every time. It also tells anyone who can measure how long it took roughly how many leading bytes of presented were correct — and that is enough to recover expected one byte at a time, without ever guessing the whole thing at once. This post is about why that leak exists, how a remote attacker turns it into a forged token, and the one-line fix that closes it.
The real question
A licensing system compares secrets constantly. An activation endpoint compares the code a customer submits against the one on record. An offline verifier compares the signature tag on a license against the tag it recomputes. A device-binding check compares a presented proof against an expected value. In every case one side is a secret and the other is supplied by whoever is holding the software — which, for a licensing product, is sometimes an attacker trying to manufacture a valid credential.
The question is not whether the comparison returns the correct boolean. It does. The question is what else it reveals while returning it.
Why early-exit leaks
Look again at the loop. It returns false the instant it finds a mismatching byte. If the first byte is wrong, it does one comparison and returns. If the first thirty bytes are right and the thirty-first is wrong, it does thirty-one comparisons and returns. The number of iterations — and therefore the wall-clock time — is a direct function of the length of the matching prefix.
That is not an implementation accident you can optimize away; it is what the IL says to do. The C# loop compiles to a body that branches out the moment the bytes differ:
// for (int i = 0; ...) if (presented[i] != expected[i]) return false;
IL_000a: ldarg.0
IL_000b: ldloc.0
IL_000c: ldelem.u1
IL_000d: ldarg.1
IL_000e: ldloc.0
IL_000f: ldelem.u1
IL_0010: beq.s IL_0016 // bytes equal → continue the loop
IL_0012: ldc.i4.0
IL_0013: ret // bytes differ → return false NOW
IL_0016: ... // i++, loop
beq.s is the early exit. The jitted code keeps that shape — a conditional branch per byte, taken as soon as a pair differs — so the method's duration carries the length of the matching prefix straight through to the caller. SequenceEqual, string.Equals, == on strings, memcmp underneath them: all of them short-circuit the same way, because for ordinary use returning early is the right thing to do.
Turning the leak into a forgery
Suppose an attacker can submit a candidate token to an activation endpoint and time the reply. They fix every byte but the first, then try all 256 values for byte 0. Two hundred fifty-five of them mismatch at position 0 and the comparison returns after one iteration. One of them matches at position 0 and the comparison proceeds to position 1 before failing — measurably, if only barely, longer. That is byte 0 recovered. Now they freeze byte 0 at the winning value and sweep byte 1, and so on.
The arithmetic is the whole point. Guessing a 32-byte token all at once is 256^32 work — it never finishes. Recovering it a byte at a time is at most 256 × 32 ≈ 8,200 guesses, because each position is confirmed independently by its timing before moving to the next. An intractable search has become a trivial one, and no cryptography was broken to do it — the comparison told the attacker when each byte was right.
Early-exit comparison returns at the first mismatch, so its running time encodes the length of the matching prefix. Constant-time comparison XORs every byte pair into an accumulator over the full length and tests once at the end, so timing reveals nothing about where the inputs differ.The fix: accumulate, don't branch
The cure is to never let the data decide when to stop. Walk the whole length every time, fold each byte-pair difference into an accumulator, and only look at the result after the last byte. .NET ships exactly this as CryptographicOperations.FixedTimeEquals:
using System.Security.Cryptography;
static bool TokenMatches(ReadOnlySpan<byte> presented, ReadOnlySpan<byte> expected)
=> CryptographicOperations.FixedTimeEquals(presented, expected);
Conceptually it is the branch-free loop you would otherwise have to get exactly right by hand:
// What FixedTimeEquals does, in spirit — no data-dependent branch, no early return.
static bool ConstantTimeEquals(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b)
{
if (a.Length != b.Length) return false; // see the length caveat below
int diff = 0;
for (int i = 0; i < a.Length; i++)
diff |= a[i] ^ b[i]; // XOR is 0 only when the bytes are equal
return diff == 0; // one test, after touching every byte
}
Two bytes that are equal XOR to zero and contribute nothing; any difference sets a bit in diff that no later iteration can clear. The loop runs the same number of iterations whether the inputs match at byte 0, byte 31, or nowhere, so the running time no longer encodes the matching prefix. Use the framework method rather than this hand-rolled one — the real implementation is careful to keep the compare off the optimizer's radar so a clever jit cannot reintroduce a branch — but the shape is exactly this.
Because the method takes ReadOnlySpan<byte>, it compares hashes, MAC tags, and stackalloc buffers with no allocation:
// Verify an activation code against the stored reference, in constant time.
Span<byte> presentedHash = stackalloc byte[32];
Span<byte> expectedHash = stackalloc byte[32];
SHA256.HashData(presentedCodeUtf8, presentedHash);
SHA256.HashData(expectedCodeUtf8, expectedHash);
bool ok = CryptographicOperations.FixedTimeEquals(presentedHash, expectedHash);
When you are done with a secret buffer, scrub it instead of waiting for the GC. The companion method CryptographicOperations.ZeroMemory clears a span in a way the optimizer is not allowed to elide as a dead store:
CryptographicOperations.ZeroMemory(expectedHash);
This is the comparison Keyright's own SDK uses on every secret-versus-input path, from activation-code checks to signature-tag verification, and it is the comparison we recommend for any integration — Community Edition included — that validates a secret against a value the holder of the software supplies.
The length caveat, handled
FixedTimeEquals is constant-time in the contents of its inputs, not in their length. It runs in time proportional to how many bytes it walks, so two things still leak: an input of the wrong length is distinguishable from one of the right length, and the absolute time scales with how long the secret is. For fixed-width secrets this is a non-problem — a 32-byte MAC is always 32 bytes, so every comparison is identical in length by construction, and that is the common case.
It becomes real when the inputs are variable-length — comparing a submitted string of attacker-chosen length against a stored secret. The robust pattern is to collapse both sides to a fixed-width digest first and compare the digests:
// Variable-length inputs → hash to a fixed 32 bytes, then compare the hashes.
Span<byte> h1 = stackalloc byte[32];
Span<byte> h2 = stackalloc byte[32];
SHA256.HashData(presentedUtf8, h1);
SHA256.HashData(secretUtf8, h2);
bool ok = CryptographicOperations.FixedTimeEquals(h1, h2);
Now the comparison is always 32 bytes wide regardless of what was submitted, and the length channel is closed along with the content channel.
When this does not matter
Precision cuts both ways: constant-time comparison is the right tool in a narrow set of cases and unnecessary noise everywhere else.
-
Both sides are local and trusted. Comparing two values you computed yourself, that no attacker sees or influences — a cached configuration hash against a recomputed one, two internal record identifiers — has no timing channel worth closing. There is no remote measurement and no secret being guessed. Ordinary
==orSequenceEqualis correct and clearer; reach forFixedTimeEqualshere and you are only obscuring intent. - A mismatch is not secret. If the thing being compared is public and getting it wrong reveals nothing an attacker could not already compute, the timing tells them nothing useful.
- It is not a rate-limiter. Closing the timing side channel stops an attacker from learning the secret byte-by-byte, but an online endpoint that cheerfully answers unlimited guesses is still a problem. Constant-time comparison and throttling, lockouts, and audit on the activation path are complementary — one removes the oracle, the other removes the opportunity to query it at scale. Ship both.
The test for whether you need it is one sentence: am I comparing a secret against a value an attacker supplies, and can they observe whether it was accepted? If yes, use FixedTimeEquals. If no, do not bother.
Takeaway
==, SequenceEqual, and string.Equals are correct comparisons and wrong security primitives, because they stop at the first difference and leak the length of the matching prefix as time — enough for a remote attacker to reconstruct a token or MAC one byte per few hundred guesses. CryptographicOperations.FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) removes the leak by doing the same branch-free work no matter where the inputs differ; hash variable-length inputs to a fixed width first so length cannot leak either, scrub secret buffers with ZeroMemory, and keep the rate-limit on the endpoint regardless. It is one method call, on exactly the paths where one side is a secret and the other is attacker-supplied — and nowhere else.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.