csharp / expert
Snippet
Side-Channel Resistant Validation
Expert-level security in C# requires protecting against side-channel attacks. Standard equality operators return early upon finding a mismatch, leaking information via execution time. Fixed-time comparison ensures the entire buffer is processed, making it impossible for an attacker to guess the secret by measuring latency.
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
using System.Security.Cryptography;public class SecurityVault{public static bool SecureCompare(byte[] a, byte[] b){// Prevents timing attacks by ensuring comparison time is constant// regardless of where the first mismatch occurs.return CryptographicOperations.FixedTimeEquals(a, b);}public static bool ManualFixedTimeCompare(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right){if (left.Length != right.Length) return false;int accumulator = 0;for (int i = 0; i < left.Length; i++){accumulator |= left[i] ^ right[i];}return accumulator == 0;}}
Breakdown
1
CryptographicOperations.FixedTimeEquals(a, b);
Uses specialized BCL methods to perform constant-time comparison of byte sequences.
2
accumulator |= left[i] ^ right[i];
Uses the XOR operator and a bitwise OR accumulator to check for differences without branching.