csharp / intermediate
Snippet
Secure Byte Comparison to Prevent Timing Attacks
In security contexts like password hashing, comparing bytes must take the same amount of time regardless of whether the arrays match. A standard 'Equals' method returns early on the first mismatch, leaking information that attackers can use to guess values via timing measurements.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
public static bool ConstantTimeEquals(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];
Uses XOR to check for differences and bitwise OR to accumulate them without branching.
2
return result == 0;
Only returns true if all XOR operations resulted in zero (no differences found).