csharp / expert
Snippet
Constant-Time Buffering for Timing Attack Mitigation
In security-critical code, comparing hashes or keys must happen in constant time to prevent side-channel timing attacks. Using 'FixedTimeEquals' ensures that the comparison duration does not depend on how many leading bytes match. The Wipe method uses compiler attributes to prevent the clearing operation from being optimized away.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System.Runtime.CompilerServices;using System.Security.Cryptography;public static class SecurityUtils{public static bool SecureCompare(byte[] a, byte[] b){if (a == null || b == null || a.Length != b.Length)return false;return CryptographicOperations.FixedTimeEquals(a, b);}[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]public static void WipeSensitiveData(byte[] data){Array.Clear(data, 0, data.Length);}}
Breakdown
1
CryptographicOperations.FixedTimeEquals(a, b)
Performs a comparison where every byte is checked regardless of earlier mismatches.
2
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
Directs the JIT compiler not to remove the 'Wipe' call, which it might otherwise see as redundant.