Table of Contents

Class CryptographicOperations

Namespace
CryptoHives.Foundation.Security.Cryptography
Assembly
CryptoHives.Foundation.Security.Cryptography.dll

Operations on secret data that a compiler is not permitted to optimize: erasing a buffer, and comparing two in constant time.

public static class CryptographicOperations
Inheritance
CryptographicOperations
Inherited Members

Remarks

Prefer ZeroMemory(Span<byte>) over Clear(Array, int, int) or Span<T>.Clear() for anything secret. Clearing a buffer you are about to discard is a dead store: nothing reads the zeros back, so a compiler or JIT is entitled to delete the write entirely and leave the key, password or plaintext sitting in memory. Likewise prefer FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) over SequenceEqual when checking a MAC or a tag, so the comparison cannot leak how many leading bytes matched.

Methods

FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>)

Compares two byte spans in constant time, to prevent timing attacks.

public static bool FixedTimeEquals(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)

Parameters

left ReadOnlySpan<byte>

First span to compare.

right ReadOnlySpan<byte>

Second span to compare.

Returns

bool

true if the spans are equal, false otherwise.

ZeroMemory(byte[])

Fills an array with zeros in a way that is not subject to compiler optimizations.

public static void ZeroMemory(byte[] buffer)

Parameters

buffer byte[]

The buffer to clear. A null array is ignored.

ZeroMemory(char[])

Fills a character array with zeros in a way that is not subject to compiler optimizations.

public static void ZeroMemory(char[] buffer)

Parameters

buffer char[]

The buffer to clear. A null array is ignored.

ZeroMemory(Span<byte>)

Fills a span with zeros in a way that is not subject to compiler optimizations.

public static void ZeroMemory(Span<byte> buffer)

Parameters

buffer Span<byte>

The buffer to clear.

ZeroMemory(Span<char>)

Fills a character span with zeros in a way that is not subject to compiler optimizations.

public static void ZeroMemory(Span<char> buffer)

Parameters

buffer Span<char>

The buffer to clear.

Remarks

Character buffers reach cryptographic code as passwords and as PEM text carrying private keys. Both are secret, and both are erasable only because they are char storage rather than a string.