Background and motivation
a couple of times it has come up that I needed to answer this question: I need to determine if this buffer is all zero or not, and do it in a fixed-time manner.
You can do that with something like:
CryptographicOperations.FixedTimeEquals(input, [0, 0, 0, 0, 0])
But that forces materializing some second parameter of zeros.
API Proposal
namespace System.Security.Cryptography;
public static partial class CryptographicOperations {
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
public static bool FixedTimeIsZeros(ReadOnlySpan<byte> source);
}
The implementation will just accumulate bits with | and return true if the accumulated value is zero.
API Usage
bool isZeros = CryptographicOperations.FixedTimeIsZeros(someInput);
Alternative Designs
We could make this genetic against any scalar:
public static bool FixedTimeEquals(ReadOnlySpan<byte> input, byte comparer);
Which basically would just subtract the comparer from each element, then accumulate bits. This would allow to to do something like:
bool allZeros = FixedTimeEquals(input, 0);
bool allOnes = FixedTimeEquals(input, 1);
Risks
No response
Background and motivation
a couple of times it has come up that I needed to answer this question: I need to determine if this buffer is all zero or not, and do it in a fixed-time manner.
You can do that with something like:
CryptographicOperations.FixedTimeEquals(input, [0, 0, 0, 0, 0])But that forces materializing some second parameter of zeros.
API Proposal
The implementation will just accumulate bits with
|and return true if the accumulated value is zero.API Usage
Alternative Designs
We could make this genetic against any scalar:
Which basically would just subtract the comparer from each element, then accumulate bits. This would allow to to do something like:
Risks
No response