0 day streak
csharp / expert
Snippet

Constant-Time Sequence Comparison

In cryptographic contexts, comparing secrets (like hashes or signatures) using standard equality operators can leak information via timing side-channels. A 'short-circuit' comparison returns faster if the first byte differs, allowing attackers to brute-force values byte-by-byte. Constant-time comparison ensures the operation takes the same duration regardless of where the difference occurs by using bitwise XOR accumulation.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
public static class SecurityUtils
{
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
public static bool FixedTimeEquals(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)
{
if (left.Length != right.Length) return false;
int result = 0;
for (int i = 0; i < left.Length; i++)
{
result |= left[i] ^ right[i];
}
return result == 0;
}
// Standard library alternative available in System.Security.Cryptography
public static bool SecureCompare(byte[] a, byte[] b) =>
CryptographicOperations.FixedTimeEquals(a, b);
}
Breakdown
1
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
Prevents the JIT compiler from optimizing away the loop or inlining the method, which could re-introduce timing leaks.
2
result |= left[i] ^ right[i];
Uses XOR to check for differences; if any bit differs, 'result' becomes non-zero and stays non-zero until the end of the loop.