HashAlgorithmExtensions Class
Definition
- Namespace
- Bodu.Security.Cryptography.Extensions
- Assembly
- Bodu.Security.Cryptography.dll
- Package
- Bodu.Security.Cryptography 1.2.0
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 chainedTransformBlocksequence 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 whenalgorithmitself 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
algorithmHashAlgorithmThe HashAlgorithm instance receiving the data. Must not be null.
dataReadOnlySpan<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
algorithmis 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
algorithmHashAlgorithmThe hash algorithm to use. Must not be null.
sourceStreamThe stream whose bytes are appended to the current hash state. Must not be null.
bufferSizeintThe number of bytes read per iteration. Must be greater than zero. Defaults to 4096.
cancellationTokenCancellationTokenToken used to cancel the read loop. When signaled, the current ReadAsync(Memory<byte>, CancellationToken) is canceled and OperationCanceledException is propagated to the caller.
Returns
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
algorithmorsourceis null.- ArgumentOutOfRangeException
bufferSizeis less than or equal to zero.- OperationCanceledException
cancellationTokenwas signaled before or during the read loop.- IOException
sourcethrew 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input data to hash. A null value causes the method to return false.
expectedHashbyte[]The expected hash value to compare against. A null value causes the method to return false.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input data to hash. A null value causes the method to return false.
expectedHexstringThe 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 ifexpectedHexis not a valid hexadecimal string.
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe input stream to read and hash. A null value causes the method to return false.
expectedHashbyte[]The expected hash value as a byte array. A null value causes the method to return false.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe input stream to read and hash. A null value causes the method to return false.
expectedHexstringThe 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 ifexpectedHexis not a valid hexadecimal string.
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputReadOnlyMemory<byte>The memory buffer containing the input data to hash.
expectedHashbyte[]The expected hash value as a byte array. A null value causes the method to return false.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputReadOnlySpan<byte>The span of input bytes to hash.
expectedHashReadOnlySpan<byte>The expected hash as a read-only byte span.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputstringThe plain-text string to encode and hash. A null value causes the method to return false.
encodingEncodingThe encoding used to convert
inputto bytes. A null value causes the method to return false.expectedHashbyte[]The expected hash value as a byte array. A null value causes the method to return false.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input data to hash. A null value causes the task to resolve to false.
expectedHashbyte[]The expected hash value as a byte array. A null value causes the task to resolve to false.
cancellationTokenCancellationTokenPre-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
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input data to hash. A null value causes the task to resolve to false.
expectedHexstringThe expected hash as a hexadecimal string. A null value causes the task to resolve to false.
cancellationTokenCancellationTokenPre-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 ifexpectedHexis 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
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe stream to read and hash. A null value causes the task to resolve to false.
expectedHashbyte[]The expected hash value as a byte array. A null value causes the task to resolve to false.
cancellationTokenCancellationTokenA 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
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe stream to read and hash asynchronously. A null value causes the task to resolve to false.
expectedHashReadOnlyMemory<byte>The expected hash value as a ReadOnlyMemory<T> of bytes.
cancellationTokenCancellationTokenA 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
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe readable stream to hash asynchronously. A null value causes the task to resolve to false.
expectedHexstringThe expected hash as a hexadecimal string. A null value causes the task to resolve to false.
cancellationTokenCancellationTokenA 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 ifexpectedHexis not a valid hexadecimal string.
Exceptions
- ArgumentNullException
Thrown if
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputstringThe input string to encode and hash. A null value causes the task to resolve to false.
encodingEncodingThe character encoding used to convert
inputto bytes. A null value causes the task to resolve to false.expectedHashbyte[]The expected hash value as a byte array. A null value causes the task to resolve to false.
cancellationTokenCancellationTokenPre-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
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input byte array whose hash will be computed. Must not be null.
expectedHashbyte[]The expected hash value as a byte array. Must not be null.
Returns
Remarks
Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.
Exceptions
- ArgumentNullException
Thrown if
algorithm,input, orexpectedHashis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input byte array whose hash will be computed. Must not be null.
expectedHexstringThe 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 ifexpectedHexis 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, orexpectedHexis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe input stream to read and hash. Must not be null and must be readable.
expectedHashbyte[]The expected hash value as a byte array. Must not be null.
Returns
Remarks
Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.
Exceptions
- ArgumentNullException
Thrown if
algorithm,stream, orexpectedHashis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe input stream to read and hash. Must not be null and must be readable.
expectedHexstringThe 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 ifexpectedHexis 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, orexpectedHexis 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
algorithmHashAlgorithmThe HashAlgorithm used to compute the hash. Must not be null.
inputReadOnlyMemory<byte>The memory buffer containing the input data to hash.
expectedHashbyte[]The expected hash value as a byte array. Must not be null.
Returns
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
algorithmorexpectedHashis 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
algorithmHashAlgorithmThe HashAlgorithm used to compute the hash. Must not be null.
inputReadOnlySpan<byte>The input span of bytes to hash.
expectedHashReadOnlySpan<byte>The expected hash as a read-only span of bytes.
Returns
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
algorithmis 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
algorithmHashAlgorithmThe HashAlgorithm used to compute the hash. Must not be null.
textstringThe input string to encode and hash. Must not be null.
encodingEncodingThe encoding used to convert
textto bytes. Must not be null.expectedHashbyte[]The expected hash as a byte array. Must not be null.
Returns
Remarks
Comparison is performed using FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) to mitigate timing side-channel attacks.
Exceptions
- ArgumentNullException
Thrown if
algorithm,text,encoding, orexpectedHashis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe stream to read and hash asynchronously. Must not be null and must be readable.
expectedHashbyte[]The expected hash value as a byte array. Must not be null.
cancellationTokenCancellationTokenA 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, orexpectedHashis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe readable stream to hash asynchronously. Must not be null.
expectedHashReadOnlyMemory<byte>The expected hash value as a ReadOnlyMemory<T> of bytes.
cancellationTokenCancellationTokenA 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
algorithmorstreamis 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
algorithmHashAlgorithmThe HashAlgorithm instance used to compute the hash. Must not be null.
streamStreamThe readable stream to hash asynchronously. Must not be null.
expectedHexstringThe expected hash as a hexadecimal string. Case-insensitive. Must not be null.
cancellationTokenCancellationTokenA 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 ifexpectedHexis 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, orexpectedHexis null.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |