Skip to content

[API Proposal]: CryptographicOperations.FixedTimeIsZeros #127584

@vcsjones

Description

@vcsjones

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions