Table of Contents

HashAlgorithmExtensions Class

Definition

Namespace
Bodu.Security.Cryptography.Extensions
Assembly
Bodu.Security.Cryptography.dll
Package
Bodu.Security.Cryptography 1.2.0
Source
HashAlgorithmExtensions.AppendData.cs

Extends HashAlgorithm with incremental input, async hashing of streams, and constant-time verification against expected digests supplied as bytes, spans, memory, or hex strings.

public static class HashAlgorithmExtensions
Inheritance
HashAlgorithmExtensions
Inherited Members

Remarks

The HashAlgorithm base type exposes a low-level API: TransformBlock / TransformFinalBlock for incremental input, and ComputeHash(byte[]) for one-shot work. Production code that hashes streams, verifies downloads, or matches user-supplied digests ends up writing the same boilerplate repeatedly: read the stream into a buffer, push it through the algorithm, and compare the result with FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to avoid timing leaks. This class collapses that boilerplate into a small, named API surface while keeping every comparison constant-time.

The API surface clusters into three groups:

  • Append AppendData / AppendDataAsync - feed a span or stream into the algorithm's running state, equivalent to a chained TransformBlock sequence but cancellation-aware in the async form.
  • Throwing verification VerifyHash / VerifyHashAsync - hash an input (byte array, span, memory, stream, or string with a chosen Encoding) and compare the digest against an expected value given as bytes or as a hexadecimal string. Throws on a malformed input or hex.
  • Try-pattern verification TryVerifyHash / TryVerifyHashAsync - non-throwing counterparts that return false for any null data parameter (input, expectedHash, expectedHex, encoding, stream), for malformed expected hashes, and for any internal failure; true is returned only when the inputs round-trip and match. ArgumentNullException is thrown only when algorithm itself is null. Suitable when the expected hash is user-supplied.

Every digest comparison routes through FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) so an attacker cannot infer a partial-match by timing the call. The async overloads honor CancellationToken at every read boundary. HashAlgorithm instances are stateful and reset after each verification or compute call; they are not thread-safe, so share instances only behind explicit synchronization. Stream overloads do not dispose the supplied Stream.

For non-cryptographic algorithms (CRC, xxHash, Fletcher, …) prefer the NonCryptographicHashAlgorithmExtensions companion in Bodu.IO.Hashing; both surfaces follow the same naming so call sites read identically.

using System.Security.Cryptography;
using System.Text;
using Bodu.Security.Cryptography.Extensions;

using var sha = SHA256.Create();

// 1. Verify a UTF-8 string against an expected digest, throwing if anything is wrong.
byte[] expected =
    Convert.FromHexString("dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f");
bool match = sha.VerifyHash("Hello, World!", Encoding.UTF8, expected);

// 2. Stream-verify a downloaded file against a hex digest, without throwing on malformed hex.
using FileStream fs = File.OpenRead("payload.bin");
bool ok = sha.TryVerifyHash(fs, expectedHex: "ba7816bf...");

// 3. Cancellable async verification of a network stream against a known digest.
await using Stream net = response.Content.ReadAsStream();
bool verified = await sha.VerifyHashAsync(net, expected, cancellationToken);

Methods

AppendData(HashAlgorithm, ReadOnlySpan<byte>)

Feeds a span of bytes into the ongoing hash computation of the specified HashAlgorithm without finalizing it.

public static void AppendData(this HashAlgorithm algorithm, ReadOnlySpan<byte> data)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance receiving the data. Must not be null.

data ReadOnlySpan<byte>

The span of bytes to feed into the hash computation.

Remarks

This method is intended for use in incremental hashing scenarios where data is supplied in multiple segments. The caller is responsible for calling TransformFinalBlock(byte[], int, int) to complete the hash and obtain the result.

An ArrayPool<T> buffer is used internally to bridge the span into the array-based TransformBlock(byte[], int, int, byte[], int) API. The buffer is cleared and returned to the pool in a finally block so the input data cannot be observed by a subsequent pool consumer even if TransformBlock(byte[], int, int, byte[], int) throws.

If data is empty, this method returns without performing any work.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

AppendDataAsync(HashAlgorithm, Stream, int, CancellationToken)

Asynchronously reads all bytes from source and feeds them into the hash accumulator via TransformBlock(byte[], int, int, byte[], int), without finalizing the computation.

public static Task AppendDataAsync(this HashAlgorithm algorithm, Stream source, int bufferSize = 4096, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The hash algorithm to use. Must not be null.

source Stream

The stream whose bytes are appended to the current hash state. Must not be null.

bufferSize int

The number of bytes read per iteration. Must be greater than zero. Defaults to 4096.

cancellationToken CancellationToken

Token used to cancel the read loop. When signaled, the current ReadAsync(Memory<byte>, CancellationToken) is canceled and OperationCanceledException is propagated to the caller.

Returns

Task

A Task that completes when all bytes have been fed into the accumulator.

Remarks

This method is the asynchronous counterpart to AppendData(HashAlgorithm, ReadOnlySpan<byte>). It allows large or streaming sources to be incorporated into an incremental hash computation without blocking the calling thread.

Because only TransformBlock(byte[], int, int, byte[], int) is called, the hash state is not finalized after this method returns. The caller is responsible for calling TransformFinalBlock(byte[], int, int) when all data has been supplied.

Multiple AppendDataAsync(HashAlgorithm, Stream, int, CancellationToken) calls - and calls interleaved with the synchronous AppendData(HashAlgorithm, ReadOnlySpan<byte>) - accumulate correctly because all of them delegate to TransformBlock(byte[], int, int, byte[], int).

The read buffer is rented from Shared and returned - with its contents zeroed - in all exit paths, including cancellation and exception propagation.

Exceptions

ArgumentNullException

algorithm or source is null.

ArgumentOutOfRangeException

bufferSize is less than or equal to zero.

OperationCanceledException

cancellationToken was signaled before or during the read loop.

IOException

source threw an IOException during a read.

TryVerifyHash(HashAlgorithm, byte[], byte[])

Attempts to compute and verify the hash of a byte array against the expected hash value.

public static bool TryVerifyHash(this HashAlgorithm algorithm, byte[] input, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input byte[]

The input data to hash. A null value causes the method to return false.

expectedHash byte[]

The expected hash value to compare against. A null value causes the method to return false.

Returns

bool

true if the computed hash matches expectedHash; otherwise, false.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHash(HashAlgorithm, byte[], string)

Attempts to compute and verify the hash of a byte array against an expected hexadecimal hash string.

public static bool TryVerifyHash(this HashAlgorithm algorithm, byte[] input, string expectedHex)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input byte[]

The input data to hash. A null value causes the method to return false.

expectedHex string

The expected hash as a hexadecimal string. A null value causes the method to return false.

Returns

bool

true if the computed hash matches expectedHex; otherwise, false. Returns false if expectedHex is not a valid hexadecimal string.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHash(HashAlgorithm, Stream, byte[])

Attempts to compute and verify the hash of a stream against the expected hash value.

public static bool TryVerifyHash(this HashAlgorithm algorithm, Stream stream, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The input stream to read and hash. A null value causes the method to return false.

expectedHash byte[]

The expected hash value as a byte array. A null value causes the method to return false.

Returns

bool

true if the stream produces a matching hash; otherwise, false.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHash(HashAlgorithm, Stream, string)

Attempts to compute and verify the hash of a stream against the expected hexadecimal hash string.

public static bool TryVerifyHash(this HashAlgorithm algorithm, Stream stream, string expectedHex)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The input stream to read and hash. A null value causes the method to return false.

expectedHex string

The expected hash value as a hexadecimal string. A null value causes the method to return false.

Returns

bool

true if the stream hash matches expectedHex; otherwise, false. Returns false if expectedHex is not a valid hexadecimal string.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHash(HashAlgorithm, ReadOnlyMemory<byte>, byte[])

Attempts to compute and verify the hash of a memory buffer against the expected hash value.

public static bool TryVerifyHash(this HashAlgorithm algorithm, ReadOnlyMemory<byte> input, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input ReadOnlyMemory<byte>

The memory buffer containing the input data to hash.

expectedHash byte[]

The expected hash value as a byte array. A null value causes the method to return false.

Returns

bool

true if the computed hash matches expectedHash; otherwise, false.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHash(HashAlgorithm, ReadOnlySpan<byte>, ReadOnlySpan<byte>)

Attempts to compute and verify the hash of a span of bytes against the expected hash span.

public static bool TryVerifyHash(this HashAlgorithm algorithm, ReadOnlySpan<byte> input, ReadOnlySpan<byte> expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input ReadOnlySpan<byte>

The span of input bytes to hash.

expectedHash ReadOnlySpan<byte>

The expected hash as a read-only byte span.

Returns

bool

true if the computed hash matches expectedHash; otherwise, false.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHash(HashAlgorithm, string, Encoding, byte[])

Attempts to compute and verify the hash of an encoded string against the expected hash value.

public static bool TryVerifyHash(this HashAlgorithm algorithm, string input, Encoding encoding, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input string

The plain-text string to encode and hash. A null value causes the method to return false.

encoding Encoding

The encoding used to convert input to bytes. A null value causes the method to return false.

expectedHash byte[]

The expected hash value as a byte array. A null value causes the method to return false.

Returns

bool

true if the computed hash matches expectedHash; otherwise, false.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHashAsync(HashAlgorithm, byte[], byte[], CancellationToken)

Attempts to verify the hash of a byte array against the expected hash value, exposed as a Task<TResult> for API symmetry with the stream-based asynchronous overloads.

public static Task<bool> TryVerifyHashAsync(this HashAlgorithm algorithm, byte[] input, byte[] expectedHash, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input byte[]

The input data to hash. A null value causes the task to resolve to false.

expectedHash byte[]

The expected hash value as a byte array. A null value causes the task to resolve to false.

cancellationToken CancellationToken

Pre-checked before delegation. If already canceled, the task resolves to false; the synchronous delegate cannot otherwise observe the token.

Returns

Task<bool>

A task that evaluates to true if the computed hash matches expectedHash; otherwise, false.

Remarks

This overload performs no I/O. It delegates to TryVerifyHash(HashAlgorithm, byte[], byte[]) and wraps the result in a completed Task<TResult>, so the operation completes synchronously.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHashAsync(HashAlgorithm, byte[], string, CancellationToken)

Attempts to verify the hash of a byte array against the expected hexadecimal hash string, exposed as a Task<TResult> for API symmetry with the stream-based asynchronous overloads.

public static Task<bool> TryVerifyHashAsync(this HashAlgorithm algorithm, byte[] input, string expectedHex, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input byte[]

The input data to hash. A null value causes the task to resolve to false.

expectedHex string

The expected hash as a hexadecimal string. A null value causes the task to resolve to false.

cancellationToken CancellationToken

Pre-checked before delegation. If already canceled, the task resolves to false; the synchronous delegate cannot otherwise observe the token.

Returns

Task<bool>

A task that evaluates to true if the computed hash matches expectedHex; otherwise, false. Returns false if expectedHex is not a valid hexadecimal string.

Remarks

This overload performs no I/O. It delegates to TryVerifyHash(HashAlgorithm, byte[], string) and wraps the result in a completed Task<TResult>, so the operation completes synchronously.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHashAsync(HashAlgorithm, Stream, byte[], CancellationToken)

Attempts to asynchronously compute and verify the hash of a stream against the expected hash value.

public static Task<bool> TryVerifyHashAsync(this HashAlgorithm algorithm, Stream stream, byte[] expectedHash, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The stream to read and hash. A null value causes the task to resolve to false.

expectedHash byte[]

The expected hash value as a byte array. A null value causes the task to resolve to false.

cancellationToken CancellationToken

A token to cancel the asynchronous operation.

Returns

Task<bool>

A task that evaluates to true if the computed hash matches expectedHash; otherwise, false.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHashAsync(HashAlgorithm, Stream, ReadOnlyMemory<byte>, CancellationToken)

Attempts to asynchronously compute and verify the hash of a stream against the expected hash value held in a memory buffer.

public static Task<bool> TryVerifyHashAsync(this HashAlgorithm algorithm, Stream stream, ReadOnlyMemory<byte> expectedHash, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The stream to read and hash asynchronously. A null value causes the task to resolve to false.

expectedHash ReadOnlyMemory<byte>

The expected hash value as a ReadOnlyMemory<T> of bytes.

cancellationToken CancellationToken

A token to cancel the asynchronous operation.

Returns

Task<bool>

A task that evaluates to true if the computed hash matches expectedHash; otherwise, false.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHashAsync(HashAlgorithm, Stream, string, CancellationToken)

Attempts to asynchronously compute and verify the hash of a stream against the expected hexadecimal hash string.

public static Task<bool> TryVerifyHashAsync(this HashAlgorithm algorithm, Stream stream, string expectedHex, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The readable stream to hash asynchronously. A null value causes the task to resolve to false.

expectedHex string

The expected hash as a hexadecimal string. A null value causes the task to resolve to false.

cancellationToken CancellationToken

A token to cancel the asynchronous operation.

Returns

Task<bool>

A task that evaluates to true if the computed hash matches expectedHex; otherwise, false. Returns false if expectedHex is not a valid hexadecimal string.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

TryVerifyHashAsync(HashAlgorithm, string, Encoding, byte[], CancellationToken)

Attempts to verify the hash of an encoded string against the expected hash value, exposed as a Task<TResult> for API symmetry with the stream-based asynchronous overloads.

public static Task<bool> TryVerifyHashAsync(this HashAlgorithm algorithm, string input, Encoding encoding, byte[] expectedHash, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input string

The input string to encode and hash. A null value causes the task to resolve to false.

encoding Encoding

The character encoding used to convert input to bytes. A null value causes the task to resolve to false.

expectedHash byte[]

The expected hash value as a byte array. A null value causes the task to resolve to false.

cancellationToken CancellationToken

Pre-checked before delegation. If already canceled, the task resolves to false; the synchronous delegate cannot otherwise observe the token.

Returns

Task<bool>

A task that evaluates to true if the computed hash matches expectedHash; otherwise, false.

Remarks

This overload performs no I/O. It delegates to TryVerifyHash(HashAlgorithm, string, Encoding, byte[]) and wraps the result in a completed Task<TResult>, so the operation completes synchronously.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

VerifyHash(HashAlgorithm, byte[], byte[])

Verifies that the computed hash of the input data matches the expected hash value.

public static bool VerifyHash(this HashAlgorithm algorithm, byte[] input, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input byte[]

The input byte array whose hash will be computed. Must not be null.

expectedHash byte[]

The expected hash value as a byte array. Must not be null.

Returns

bool

true if the computed hash equals expectedHash; otherwise, false.

Remarks

Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

Exceptions

ArgumentNullException

Thrown if algorithm, input, or expectedHash is null.

VerifyHash(HashAlgorithm, byte[], string)

Verifies that the computed hash of the input data matches the expected hash value expressed as a hexadecimal string.

public static bool VerifyHash(this HashAlgorithm algorithm, byte[] input, string expectedHex)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

input byte[]

The input byte array whose hash will be computed. Must not be null.

expectedHex string

The expected hash value as a hexadecimal string. Case-insensitive. Must not be null.

Returns

bool

true if the computed hash matches expectedHex; otherwise, false. Returns false if expectedHex is not a valid hexadecimal string.

Remarks

expectedHex is decoded to bytes before comparison. The comparison is then performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

A malformed expectedHex string (one that cannot be decoded) is treated as a non-match and returns false.

Exceptions

ArgumentNullException

Thrown if algorithm, input, or expectedHex is null.

VerifyHash(HashAlgorithm, Stream, byte[])

Verifies that the computed hash of the stream matches the expected hash value.

public static bool VerifyHash(this HashAlgorithm algorithm, Stream stream, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The input stream to read and hash. Must not be null and must be readable.

expectedHash byte[]

The expected hash value as a byte array. Must not be null.

Returns

bool

true if the hash of the stream matches expectedHash; otherwise, false.

Remarks

Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

Exceptions

ArgumentNullException

Thrown if algorithm, stream, or expectedHash is null.

VerifyHash(HashAlgorithm, Stream, string)

Verifies that the computed hash of the stream matches the expected hash value expressed as a hexadecimal string.

public static bool VerifyHash(this HashAlgorithm algorithm, Stream stream, string expectedHex)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The input stream to read and hash. Must not be null and must be readable.

expectedHex string

The expected hash value as a hexadecimal string. Case-insensitive. Must not be null.

Returns

bool

true if the hash of the stream matches expectedHex; otherwise, false. Returns false if expectedHex is not a valid hexadecimal string.

Remarks

expectedHex is decoded to bytes before comparison. The comparison is then performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

A malformed expectedHex string is treated as a non-match and returns false.

Exceptions

ArgumentNullException

Thrown if algorithm, stream, or expectedHex is null.

VerifyHash(HashAlgorithm, ReadOnlyMemory<byte>, byte[])

Verifies that the computed hash of the input memory block matches the expected hash value.

public static bool VerifyHash(this HashAlgorithm algorithm, ReadOnlyMemory<byte> input, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm used to compute the hash. Must not be null.

input ReadOnlyMemory<byte>

The memory buffer containing the input data to hash.

expectedHash byte[]

The expected hash value as a byte array. Must not be null.

Returns

bool

true if the hash of input equals expectedHash; otherwise, false.

Remarks

Delegates to the VerifyHash(HashAlgorithm, ReadOnlySpan<byte>, ReadOnlySpan<byte>) overload. Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

Exceptions

ArgumentNullException

Thrown if algorithm or expectedHash is null.

VerifyHash(HashAlgorithm, ReadOnlySpan<byte>, ReadOnlySpan<byte>)

Verifies that the computed hash of the input span matches the expected hash span.

public static bool VerifyHash(this HashAlgorithm algorithm, ReadOnlySpan<byte> input, ReadOnlySpan<byte> expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm used to compute the hash. Must not be null.

input ReadOnlySpan<byte>

The input span of bytes to hash.

expectedHash ReadOnlySpan<byte>

The expected hash as a read-only span of bytes.

Returns

bool

true if the computed hash equals expectedHash; otherwise, false.

Remarks

This overload uses TryComputeHash(ReadOnlySpan<byte>, Span<byte>, out int) with an ArrayPool<T>-backed output buffer to avoid heap allocation for the computed hash. The buffer is cleared before being returned to the pool.

Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

Exceptions

ArgumentNullException

Thrown if algorithm is null.

VerifyHash(HashAlgorithm, string, Encoding, byte[])

Verifies that the computed hash of the encoded string matches the expected hash value.

public static bool VerifyHash(this HashAlgorithm algorithm, string text, Encoding encoding, byte[] expectedHash)

Parameters

algorithm HashAlgorithm

The HashAlgorithm used to compute the hash. Must not be null.

text string

The input string to encode and hash. Must not be null.

encoding Encoding

The encoding used to convert text to bytes. Must not be null.

expectedHash byte[]

The expected hash as a byte array. Must not be null.

Returns

bool

true if the hash of the encoded string equals expectedHash; otherwise, false.

Remarks

Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

Exceptions

ArgumentNullException

Thrown if algorithm, text, encoding, or expectedHash is null.

VerifyHashAsync(HashAlgorithm, Stream, byte[], CancellationToken)

Asynchronously verifies that the computed hash of a stream matches the expected hash value.

public static Task<bool> VerifyHashAsync(this HashAlgorithm algorithm, Stream stream, byte[] expectedHash, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The stream to read and hash asynchronously. Must not be null and must be readable.

expectedHash byte[]

The expected hash value as a byte array. Must not be null.

cancellationToken CancellationToken

A token to cancel the asynchronous operation.

Returns

Task<bool>

A task that evaluates to true if the computed hash equals expectedHash; otherwise, false.

Remarks

Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

If cancellationToken is already canceled on entry, an OperationCanceledException is thrown immediately before any I/O begins.

Exceptions

ArgumentNullException

Thrown if algorithm, stream, or expectedHash is null.

VerifyHashAsync(HashAlgorithm, Stream, ReadOnlyMemory<byte>, CancellationToken)

Asynchronously verifies that the computed hash of a stream matches the expected hash value held in a memory buffer.

public static Task<bool> VerifyHashAsync(this HashAlgorithm algorithm, Stream stream, ReadOnlyMemory<byte> expectedHash, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The readable stream to hash asynchronously. Must not be null.

expectedHash ReadOnlyMemory<byte>

The expected hash value as a ReadOnlyMemory<T> of bytes.

cancellationToken CancellationToken

A token to cancel the asynchronous operation.

Returns

Task<bool>

A task that evaluates to true if the computed hash equals expectedHash; otherwise, false.

Remarks

This overload supports allocation-reduced verification when the expected hash is already held in a ReadOnlyMemory<T> buffer. Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

If cancellationToken is already canceled on entry, an OperationCanceledException is thrown immediately before any I/O begins.

Exceptions

ArgumentNullException

Thrown if algorithm or stream is null.

VerifyHashAsync(HashAlgorithm, Stream, string, CancellationToken)

Asynchronously verifies that the computed hash of a stream matches the expected hexadecimal hash string.

public static Task<bool> VerifyHashAsync(this HashAlgorithm algorithm, Stream stream, string expectedHex, CancellationToken cancellationToken = default)

Parameters

algorithm HashAlgorithm

The HashAlgorithm instance used to compute the hash. Must not be null.

stream Stream

The readable stream to hash asynchronously. Must not be null.

expectedHex string

The expected hash as a hexadecimal string. Case-insensitive. Must not be null.

cancellationToken CancellationToken

A token to cancel the asynchronous operation.

Returns

Task<bool>

A task that evaluates to true if the computed hash matches expectedHex; otherwise, false. Returns false if expectedHex is not a valid hexadecimal string.

Remarks

expectedHex is decoded to bytes before comparison. The comparison is then performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.

A malformed expectedHex string is treated as a non-match and returns false.

If cancellationToken is already canceled on entry, an OperationCanceledException is thrown immediately before any I/O begins.

Exceptions

ArgumentNullException

Thrown if algorithm, stream, or expectedHex is null.

Applies to

ProductVersions
.NET8, 10