Skip to content

OnixLabs.Security.Cryptography.Hash

Matthew Layton edited this page Nov 15, 2026 · 3 revisions

Hash Struct

Represents an immutable cryptographic hash value backed by a raw byte sequence.

Namespace OnixLabs.Security.Cryptography
Assembly OnixLabs.Security.Cryptography.dll (NuGet)
Inheritance object → ValueType → Hash
Implements ICryptoPrimitive<Hash>, IValueEquatable<Hash>, IValueComparable<Hash>, IBinaryConvertible, ISpanParsable<Hash>

Definition

public readonly partial struct Hash :
    ICryptoPrimitive<Hash>,
    IValueComparable<Hash>,
    ISpanParsable<Hash>

Remarks

Hash is an algorithm-agnostic container for a cryptographic hash value. It wraps a raw byte array defensively: every constructor copies the input so that the internal state cannot be altered after construction, and the struct is declared readonly, making the type genuinely immutable.

Producing a hash

The most direct route is the family of static Compute overloads. Each overload accepts any System.Security.Cryptography.HashAlgorithm — including the SHA-3 variants provided by Sha3 — and accepts data as a byte[], a ReadOnlySpan<byte>, a Stream, an IBinaryConvertible, an ISpanBinaryConvertible, or a ReadOnlySpan<char> with an optional Encoding. An optional rounds parameter (default 1) causes the hash to be applied iteratively, which is useful for schemes such as double-SHA-256.

Types that implement the IHashable interface expose a ComputeHash(HashAlgorithm) method that delegates to Hash.Compute internally. Any IBinaryConvertible value can also be passed directly to the Compute overload that accepts that interface.

Formatting and parsing

Hash formats to and parses from Base-16 (hexadecimal) by default. The parameterless ToString() returns a lowercase hex string via Base16FormatProvider.Invariant. The ToString(IFormatProvider) overload from ICryptoPrimitive<Hash> accepts any IFormatProvider recognised by the IBaseCodec infrastructure (e.g. a Base58FormatProvider or Base64FormatProvider) to encode the underlying bytes in an alternative alphabet.

The static Parse and TryParse overloads accept both string and ReadOnlySpan<char> and default to Base16FormatProvider.Invariant when provider is null.

Equality and ordering

Equality uses CryptographicOperations.FixedTimeEquals, which runs in constant time to prevent timing-based side-channel attacks. Two Hash values are equal when their underlying byte sequences are identical. Ordering is defined by a lexicographic byte-sequence comparison via ReadOnlySpan<byte>.SequenceCompareTo.

Concatenation

The Concatenate instance method (and its static counterpart) concatenates two hashes byte-for-byte and hashes the result with the specified algorithm, which is the construction used in Merkle tree nodes.

Named hashes

Use ToNamedHash to pair a Hash with the name of the algorithm that produced it, yielding a NamedHash.

Value semantics

Hash participates fully in C# value semantics: it implements IEquatable<Hash>, IComparable<Hash>, IComparable, and the full set of comparison operators (==, !=, <, <=, >, >=).

Note The default value of Hash (produced by default(Hash) or an uninitialized field) has an empty byte array with Length = 0. It formats as an empty string and compares as less than any non-empty hash.

Examples

Computing and formatting a hash

using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;

// Compute a SHA-256 hash of a UTF-8 encoded string
using HashAlgorithm sha256 = SHA256.Create();
Hash hash = Hash.Compute(sha256, "Hello, World!"u8);

// Default ToString() produces lowercase hex
Console.WriteLine(hash);
// dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d

// Encode in an alternative format using a different IFormatProvider
// (requires a Base58FormatProvider or similar from OnixLabs.Core.Text)
// Console.WriteLine(hash.ToString(Base58FormatProvider.Bitcoin));

Parsing, comparing, and converting to NamedHash

using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;

Hash a = Hash.Parse("dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d");
Hash b = Hash.Parse("dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d");
Hash c = Hash.Parse("ba7816bf8f01cfea414140de5dae2ec73b00361bbef0469fa72a395ec7d1a4d4");

Console.WriteLine(a == b);  // True  — constant-time equality
Console.WriteLine(a == c);  // False
Console.WriteLine(a > c);   // True  — lexicographic byte order

// Attach an algorithm name and store together
NamedHash named = a.ToNamedHash(HashAlgorithmName.SHA256);
Console.WriteLine(named);
// SHA256:dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d

// Round-trip via TryParse
if (Hash.TryParse("dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d", null, out Hash parsed))
    Console.WriteLine(parsed.Length); // 32

Constructors

Constructor Description
Hash(ReadOnlySpan<byte>) Initializes a new instance from a ReadOnlySpan<byte>.
Hash(ReadOnlyMemory<byte>) Initializes a new instance from a ReadOnlyMemory<byte>.
Hash(ReadOnlySequence<byte>) Initializes a new instance from a ReadOnlySequence<byte>.
Hash(byte, int) Initializes a new instance by repeating a single byte value for the specified length.

Hash(ReadOnlySpan<byte>)

public Hash(ReadOnlySpan<byte> value)

Initializes a new instance of the Hash struct from the specified span.

Parameter Type Description
value ReadOnlySpan<byte> The byte span from which to initialize the hash. A defensive copy is made; the caller's span is not retained.

Hash(ReadOnlyMemory<byte>)

public Hash(ReadOnlyMemory<byte> value)

Initializes a new instance of the Hash struct from the specified memory region.

Parameter Type Description
value ReadOnlyMemory<byte> The byte memory region from which to initialize the hash. A defensive copy is made.

Hash(ReadOnlySequence<byte>)

public Hash(ReadOnlySequence<byte> value)

Initializes a new instance of the Hash struct from the specified byte sequence. The sequence is flattened into a single contiguous copy.

Parameter Type Description
value ReadOnlySequence<byte> The byte sequence from which to initialize the hash.

Hash(byte, int)

public Hash(byte value, int length)

Initializes a new instance of the Hash struct by filling a new array of the specified length with a single repeated byte value.

Parameter Type Description
value byte The byte value to repeat.
length int The length of the resulting hash in bytes.

Exceptions

Exception Condition
ArgumentOutOfRangeException length is negative.

Properties

Property Type Description
Length int Gets the length of the hash value in bytes.

Length

public int Length { get; }

Gets the number of bytes in the underlying hash value. Returns 0 for a default (uninitialized) instance.

Methods

Static Methods

Method Returns Description
Compute(HashAlgorithm, byte[], int) Hash Computes the hash of a byte[] using the specified algorithm.
Compute(HashAlgorithm, byte[], int, int, int) Hash Computes the hash of a sub-range of a byte[].
Compute(HashAlgorithm, ReadOnlySpan<byte>, int) Hash Computes the hash of a ReadOnlySpan<byte>.
Compute(HashAlgorithm, ReadOnlySpan<byte>, int, int, int) Hash Computes the hash of a sub-range of a ReadOnlySpan<byte>.
Compute(HashAlgorithm, Stream, int) Hash Computes the hash of a Stream.
Compute(HashAlgorithm, IBinaryConvertible, int) Hash Computes the hash of an IBinaryConvertible value.
Compute(HashAlgorithm, ISpanBinaryConvertible, int) Hash Computes the hash of an ISpanBinaryConvertible value.
Compute(HashAlgorithm, ReadOnlySpan<char>, Encoding?, int) Hash Computes the hash of a character span encoded with the specified encoding.
Concatenate(HashAlgorithm, Hash, Hash) Hash Concatenates two hashes byte-for-byte and hashes the result.
Parse(string, IFormatProvider?) Hash Parses a string into a Hash.
Parse(ReadOnlySpan<char>, IFormatProvider?) Hash Parses a ReadOnlySpan<char> into a Hash.
TryParse(string?, IFormatProvider?, out Hash) bool Tries to parse a string into a Hash.
TryParse(ReadOnlySpan<char>, IFormatProvider?, out Hash) bool Tries to parse a ReadOnlySpan<char> into a Hash.

Instance Methods

Method Returns Description
AsReadOnlySpan() ReadOnlySpan<byte> Returns the hash bytes as a ReadOnlySpan<byte>.
AsReadOnlyMemory() ReadOnlyMemory<byte> Returns the hash bytes as a ReadOnlyMemory<byte>.
Concatenate(HashAlgorithm, Hash) Hash Concatenates this hash with another and hashes the result.
CompareTo(Hash) int Compares this instance with another Hash value.
CompareTo(object?) int Compares this instance with another object.
Equals(Hash) bool Determines whether this instance equals another Hash value using constant-time comparison.
Equals(object?) bool Determines whether this instance equals another object.
GetHashCode() int Returns a hash code derived from the content of the byte array.
ToNamedHash(string) NamedHash Creates a NamedHash from this instance using the specified algorithm name string.
ToNamedHash(HashAlgorithmName) NamedHash Creates a NamedHash from this instance using the specified HashAlgorithmName.
ToString() string Returns the lowercase Base-16 (hex) representation of the hash.
ToString(IFormatProvider) string Returns a string representation of the hash using the specified format provider.

Compute(HashAlgorithm, byte[], int)

public static Hash Compute(HashAlgorithm algorithm, byte[] data, int rounds = 1)

Computes the hash of the specified byte[] using the given algorithm, optionally applying the algorithm for multiple rounds.

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
data byte[] The input data to hash.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified input data.

Compute(HashAlgorithm, byte[], int, int, int)

public static Hash Compute(HashAlgorithm algorithm, byte[] data, int offset, int count, int rounds = 1)

Computes the hash of a sub-range of the specified byte[].

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
data byte[] The source byte array.
offset int The zero-based index into data at which to begin reading.
count int The number of bytes to read from data.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified input data.

Compute(HashAlgorithm, ReadOnlySpan<byte>, int)

public static Hash Compute(HashAlgorithm algorithm, ReadOnlySpan<byte> data, int rounds = 1)

Computes the hash of the specified ReadOnlySpan<byte>.

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
data ReadOnlySpan<byte> The input data to hash.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified input data.

Compute(HashAlgorithm, ReadOnlySpan<byte>, int, int, int)

public static Hash Compute(HashAlgorithm algorithm, ReadOnlySpan<byte> data, int offset, int count, int rounds = 1)

Computes the hash of a sub-range of the specified ReadOnlySpan<byte>.

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
data ReadOnlySpan<byte> The source span.
offset int The zero-based index into data at which to begin reading.
count int The number of bytes to read from data.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified input data.

Compute(HashAlgorithm, Stream, int)

public static Hash Compute(HashAlgorithm algorithm, Stream stream, int rounds = 1)

Computes the hash of the specified Stream.

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
stream Stream The stream whose contents are hashed.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified stream.

Compute(HashAlgorithm, IBinaryConvertible, int)

public static Hash Compute(HashAlgorithm algorithm, IBinaryConvertible data, int rounds = 1)

Computes the hash of any value that implements IBinaryConvertible, using the binary representation returned by AsReadOnlySpan() or AsReadOnlyMemory().

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
data IBinaryConvertible The value whose binary representation is hashed.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified input data.

Compute(HashAlgorithm, ISpanBinaryConvertible, int)

public static Hash Compute(HashAlgorithm algorithm, ISpanBinaryConvertible data, int rounds = 1)

Computes the hash of any value that implements ISpanBinaryConvertible, using the span returned by AsReadOnlySpan().

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
data ISpanBinaryConvertible The value whose span representation is hashed.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified input data.

Compute(HashAlgorithm, ReadOnlySpan<char>, Encoding?, int)

public static Hash Compute(HashAlgorithm algorithm, ReadOnlySpan<char> data, Encoding? encoding = null, int rounds = 1)

Encodes the specified character span using encoding (defaulting to Encoding.UTF8 when null) and computes the hash of the resulting bytes.

Parameter Type Description
algorithm HashAlgorithm The algorithm used to compute the hash.
data ReadOnlySpan<char> The character data to encode and hash.
encoding Encoding? The text encoding to use, or null to use Encoding.UTF8.
rounds int The number of times to apply the algorithm iteratively. Defaults to 1.

Returns — A new Hash containing the computed hash bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the specified input data.

Concatenate(HashAlgorithm, Hash, Hash)

public static Hash Concatenate(HashAlgorithm algorithm, Hash left, Hash right)

Concatenates the bytes of left and right, then computes the hash of the combined byte sequence using the specified algorithm. This is the construction used for internal nodes in a MerkleTree.

Parameter Type Description
algorithm HashAlgorithm The algorithm used to hash the concatenated bytes.
left Hash The left hash to concatenate.
right Hash The right hash to concatenate.

Returns — A new Hash representing the hash of the concatenated byte sequences.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the concatenated values.

Parse(string, IFormatProvider?)

public static Hash Parse(string value, IFormatProvider? provider = null)

Parses the specified string into a Hash. When provider is null, Base16FormatProvider.Invariant (lowercase hex) is used.

Parameter Type Description
value string The encoded string to parse.
provider IFormatProvider? The format provider that defines the encoding alphabet, or null to use Base16FormatProvider.Invariant.

Returns — A new Hash whose bytes were decoded from value.

Exceptions

Exception Condition
FormatException value is not in a format recognised by the specified provider.

Parse(ReadOnlySpan<char>, IFormatProvider?)

public static Hash Parse(ReadOnlySpan<char> value, IFormatProvider? provider = null)

Parses the specified character span into a Hash. When provider is null, Base16FormatProvider.Invariant is used.

Parameter Type Description
value ReadOnlySpan<char> The encoded character span to parse.
provider IFormatProvider? The format provider that defines the encoding alphabet, or null to use Base16FormatProvider.Invariant.

Returns — A new Hash whose bytes were decoded from value.

Exceptions

Exception Condition
FormatException value is not in a format recognised by the specified provider.

TryParse(string?, IFormatProvider?, out Hash)

public static bool TryParse(string? value, IFormatProvider? provider, out Hash result)

Tries to parse the specified string into a Hash. When provider is null, Base16FormatProvider.Invariant is used.

Parameter Type Description
value string? The encoded string to parse, or null.
provider IFormatProvider? The format provider that defines the encoding alphabet, or null to use Base16FormatProvider.Invariant.
result out Hash On return, contains the parsed Hash, or default if parsing failed.

Returns — true if parsing succeeded; otherwise, false.


TryParse(ReadOnlySpan<char>, IFormatProvider?, out Hash)

public static bool TryParse(ReadOnlySpan<char> value, IFormatProvider? provider, out Hash result)

Tries to parse the specified character span into a Hash. When provider is null, Base16FormatProvider.Invariant is used.

Parameter Type Description
value ReadOnlySpan<char> The encoded character span to parse.
provider IFormatProvider? The format provider that defines the encoding alphabet, or null to use Base16FormatProvider.Invariant.
result out Hash On return, contains the parsed Hash, or default if parsing failed.

Returns — true if parsing succeeded; otherwise, false.


AsReadOnlySpan()

public ReadOnlySpan<byte> AsReadOnlySpan()

Returns the underlying hash bytes as a ReadOnlySpan<byte>. Satisfies the ISpanBinaryConvertible contract.

Returns — A ReadOnlySpan<byte> over the internal byte array.


AsReadOnlyMemory()

public ReadOnlyMemory<byte> AsReadOnlyMemory()

Returns the underlying hash bytes as a ReadOnlyMemory<byte>. Satisfies the IMemoryBinaryConvertible contract.

Returns — A ReadOnlyMemory<byte> wrapping the internal byte array.


Concatenate(HashAlgorithm, Hash)

public Hash Concatenate(HashAlgorithm algorithm, Hash other)

Concatenates this hash with other and hashes the combined bytes. Delegates to the static Concatenate(HashAlgorithm, Hash, Hash) overload with this as left.

Parameter Type Description
algorithm HashAlgorithm The algorithm used to hash the concatenated bytes.
other Hash The hash to concatenate with this instance.

Returns — A new Hash representing the hash of the concatenated byte sequences.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the concatenated values.

CompareTo(Hash)

public int CompareTo(Hash other)

Compares this instance with another Hash value using a lexicographic byte-sequence comparison.

Parameter Type Description
other Hash The value to compare with this instance.

Returns — A negative integer if this instance precedes other, zero if they are equal, or a positive integer if this instance follows other.


CompareTo(object?)

public int CompareTo(object? obj)

Compares this instance with another object.

Parameter Type Description
obj object? The object to compare with this instance.

Returns — A signed integer indicating the relative order of this instance and obj.

Exceptions

Exception Condition
ArgumentException obj is not null and is not of type Hash.

Equals(Hash)

public bool Equals(Hash other)

Determines whether this instance is equal to another Hash value. Comparison uses CryptographicOperations.FixedTimeEquals to run in constant time, preventing timing-based side-channel attacks. Two default instances (both with a null internal array) are considered equal.

Parameter Type Description
other Hash The value to compare with this instance.

Returns — true if the underlying byte sequences are identical; otherwise, false.


Equals(object?)

public override bool Equals(object? obj)

Determines whether this instance is equal to another object.

Parameter Type Description
obj object? The object to compare with this instance.

Returns — true if obj is a Hash with an identical byte sequence; otherwise, false.


GetHashCode()

public override int GetHashCode()

Returns a hash code derived from the content of the underlying byte array. Equal values produce equal hash codes; like HashCode, the result is randomised per process and must not be persisted.

Returns — A 32-bit signed integer hash code.


ToNamedHash(string)

public NamedHash ToNamedHash(string algorithmName)

Creates a new NamedHash that pairs this hash value with the specified algorithm name string.

Parameter Type Description
algorithmName string The name of the hash algorithm that produced this hash (e.g. "SHA256").

Returns — A new NamedHash combining this Hash and algorithmName.


ToNamedHash(HashAlgorithmName)

public NamedHash ToNamedHash(HashAlgorithmName algorithmName)

Creates a new NamedHash that pairs this hash value with the specified HashAlgorithmName.

Parameter Type Description
algorithmName HashAlgorithmName The name of the hash algorithm that produced this hash.

Returns — A new NamedHash combining this Hash and algorithmName.


ToString()

public override string ToString()

Returns the lowercase Base-16 (hexadecimal) representation of the hash, using Base16FormatProvider.Invariant. For example, a 32-byte SHA-256 hash produces a 64-character hex string.

Returns — A lowercase hex string representing the hash bytes.


ToString(IFormatProvider)

public string ToString(IFormatProvider provider)

Returns a string representation of the hash encoded using the specified IFormatProvider. The provider must be one recognised by the IBaseCodec infrastructure in OnixLabs.Core.Text (such as Base16FormatProvider, Base58FormatProvider, or Base64FormatProvider).

Parameter Type Description
provider IFormatProvider The format provider that determines the encoding alphabet.

Returns — The encoded string representation of the hash bytes.

Operators

Operator Description
operator == Determines whether two Hash values are equal.
operator != Determines whether two Hash values are not equal.
operator > Determines whether the left value is greater than the right value.
operator >= Determines whether the left value is greater than or equal to the right value.
operator < Determines whether the left value is less than the right value.
operator <= Determines whether the left value is less than or equal to the right value.
implicit operator Hash(ReadOnlySpan<byte>) Implicitly converts a ReadOnlySpan<byte> to a Hash.
implicit operator Hash(ReadOnlyMemory<byte>) Implicitly converts a ReadOnlyMemory<byte> to a Hash.
implicit operator Hash(ReadOnlySequence<byte>) Implicitly converts a ReadOnlySequence<byte> to a Hash.

operator ==

public static bool operator ==(Hash left, Hash right)

Determines whether two Hash values are equal. Delegates to Equals(Hash), which uses constant-time comparison.


operator !=

public static bool operator !=(Hash left, Hash right)

Determines whether two Hash values are not equal. Returns the logical negation of Equals(Hash).


operator >

public static bool operator >(Hash left, Hash right)

Determines whether left is lexicographically greater than right. Delegates to CompareTo(Hash).


operator >=

public static bool operator >=(Hash left, Hash right)

Determines whether left is lexicographically greater than or equal to right. Delegates to CompareTo(Hash).


operator <

public static bool operator <(Hash left, Hash right)

Determines whether left is lexicographically less than right. Delegates to CompareTo(Hash).


operator <=

public static bool operator <=(Hash left, Hash right)

Determines whether left is lexicographically less than or equal to right. Delegates to CompareTo(Hash).


implicit operator Hash(ReadOnlySpan<byte>)

public static implicit operator Hash(ReadOnlySpan<byte> value)

Implicitly converts a ReadOnlySpan<byte> to a Hash by copying the span's bytes. Equivalent to calling new Hash(value).

Parameter Type Description
value ReadOnlySpan<byte> The byte span to convert.

Returns — A new Hash containing a copy of value.


implicit operator Hash(ReadOnlyMemory<byte>)

public static implicit operator Hash(ReadOnlyMemory<byte> value)

Implicitly converts a ReadOnlyMemory<byte> to a Hash by copying the memory's bytes. Equivalent to calling new Hash(value).

Parameter Type Description
value ReadOnlyMemory<byte> The byte memory region to convert.

Returns — A new Hash containing a copy of value.


implicit operator Hash(ReadOnlySequence<byte>)

public static implicit operator Hash(ReadOnlySequence<byte> value)

Implicitly converts a ReadOnlySequence<byte> to a Hash by flattening and copying the sequence's bytes. Equivalent to calling new Hash(value).

Parameter Type Description
value ReadOnlySequence<byte> The byte sequence to convert.

Returns — A new Hash containing a copy of value.

See Also

ONIXLabs .NET Library


Clone this wiki locally