csharp / intermediate
Snippet
Implementing Time-Constant Equality Checks for Security
When comparing sensitive data like password hashes, standard equality operators can leak information via the time they take to return (timing attacks). A secure comparison iterates through all elements regardless of where a mismatch is found, ensuring the execution time is constant.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static bool SecureEquals(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;}// Note: System.Security.Cryptography.CryptographicOperations.FixedTimeEquals// is the built-in way to do this in .NET.
Breakdown
1
result |= a[i] ^ b[i];
Uses XOR to check for differences without short-circuiting the loop.
2
return result == 0;
If result is non-zero, at least one bit was different, but the timing was the same.