0 day streak
csharp / expert
Snippet

Constant-Time Identity Verification

A security-critical pattern for comparing sensitive data like hashes. By using XOR and avoiding early returns, the execution time remains constant regardless of where a mismatch occurs, preventing timing attacks.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
public static bool SecureCompare(byte[] a, byte[] b)
{
if (a.Length != b.Length) return false;
int result = 0;
for (int i = 0; i < a.Length; i++)
{
result |= a[i] ^ b[i];
}
return result == 0;
}
Breakdown
1
result |= a[i] ^ b[i];
Accumulates differences using bitwise XOR without branching logic.
2
return result == 0;
Returns true only if every single byte was identical.