NonCryptographicHashAlgorithmExtensions Class
Definition
Extends NonCryptographicHashAlgorithm with one-shot hashing, streaming and async input, and constant-time hash verification - the high-level surface that NonCryptographicHashAlgorithm itself omits.
public static class NonCryptographicHashAlgorithmExtensions
- Inheritance
-
NonCryptographicHashAlgorithmExtensions
- Inherited Members
Remarks
NonCryptographicHashAlgorithm intentionally exposes only the low-level Append(ReadOnlySpan<byte>) / GetCurrentHash() primitives. Real-world callers want to ask higher-level questions: "compute the hash of this byte array", "stream-hash this file", "does this download match the expected digest?". This class adds those operations as a coherent set, mirroring the shape of HashAlgorithm so the same call patterns work whether the underlying algorithm is cryptographic (SHA-256) or non-cryptographic (CRC, xxHash, Fletcher).
The API surface clusters into four groups:
- Append
AppendData/AppendDataAsync- feed a buffer or stream into the algorithm's running state, with a tunable read-buffer size for stream input. - One-shot compute
ComputeHash/ComputeHashAsync- append, finalize, and reset in a single call, returning the digest as a freshly allocated byte array. Inputs include byte arrays, byte-array slices, ReadOnlyMemory<T>, and Stream. - Throwing verification
VerifyHash/VerifyHashAsync- compute the digest of an input and compare it against an expected value supplied as either bytes or a hexadecimal string. Returns true on match, throws on argument problems. - Try-pattern verification
TryVerifyHash/TryVerifyHashAsync- non-throwing counterparts. Suitable when the expected hash is user-supplied and a malformed input should not surface as an exception.
All hash comparisons go through
FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>)
, so verification is constant-time and safe to use against attacker-supplied digests even though the underlying
algorithm itself provides no preimage resistance. The algorithm instance is stateful and reset after each
ComputeHash or VerifyHash call, but it is not thread-safe - share instances only behind explicit
synchronization. Stream overloads do not dispose the supplied stream.
using System.IO.Hashing;
using Bodu.IO.Hashing.Extensions;
// 1. One-shot hash of a byte buffer using xxHash64.
var xx = new XxHash64();
byte[] digest = xx.ComputeHash(File.ReadAllBytes("payload.bin"));
// 2. Stream-hash a large file without loading it into memory.
using FileStream fs = File.OpenRead("payload.bin");
byte[] streamDigest = xx.ComputeHash(fs);
// 3. Verify a downloaded artefact against an expected hex digest, without throwing on a malformed string.
var crc = new Crc32();
if (crc.TryVerifyHash(File.ReadAllBytes("artefact.zip"), expectedHex: "deadbeef"))
Console.WriteLine("artefact verified");
Methods
AppendData(NonCryptographicHashAlgorithm, Stream, int)
Reads all bytes from source and feeds them into the hash accumulator via
Append(ReadOnlySpan<byte>), without finalizing the computation.
public static void AppendData(this NonCryptographicHashAlgorithm algorithm, Stream source, int bufferSize = 4096)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance receiving the data. 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.
Remarks
This method allows large or streaming sources to be incorporated into an incremental hash computation. Because only Append(ReadOnlySpan<byte>) is called, the hash state is not finalized after this method returns.
The read buffer is rented from Shared and returned in all exit paths, including exception propagation.
Exceptions
- ArgumentNullException
Thrown if
algorithmorsourceis null.- ArgumentOutOfRangeException
bufferSizeis less than or equal to zero.- IOException
sourcethrew an IOException during a read.
AppendData(NonCryptographicHashAlgorithm, ReadOnlySpan<byte>)
Feeds a span of bytes into the ongoing hash computation of the specified NonCryptographicHashAlgorithm without finalizing it.
public static void AppendData(this NonCryptographicHashAlgorithm algorithm, ReadOnlySpan<byte> data)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance receiving the data. Must not be null.
dataReadOnlySpan<byte>The span of bytes to feed into the hash computation.
Remarks
This method is a null-guarded wrapper around Append(ReadOnlySpan<byte>), intended for use in incremental hashing scenarios where data is supplied in multiple segments. Retrieve the current digest at any point by calling GetCurrentHash() or GetHashAndReset().
If data is empty, this method returns without performing any work.
Exceptions
- ArgumentNullException
Thrown if
algorithmis null.
AppendDataAsync(NonCryptographicHashAlgorithm, Stream, int, CancellationToken)
Asynchronously reads all bytes from source and feeds them into the hash accumulator via
Append(ReadOnlySpan<byte>), without finalizing the computation.
public static Task AppendDataAsync(this NonCryptographicHashAlgorithm algorithm, Stream source, int bufferSize = 4096, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe 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(NonCryptographicHashAlgorithm, Stream, int). It allows large or streaming sources to be incorporated into an incremental hash computation without blocking the calling thread.
Because only Append(ReadOnlySpan<byte>) is called, the hash state is not finalized after this method returns. The caller retrieves the digest by calling GetCurrentHash() or GetHashAndReset() when all data has been supplied.
Multiple AppendDataAsync(NonCryptographicHashAlgorithm, Stream, int, CancellationToken) calls - and calls interleaved with the synchronous AppendData(NonCryptographicHashAlgorithm, Stream, int) - accumulate correctly because both delegate to Append(ReadOnlySpan<byte>) on the same instance.
The read buffer is rented from Shared and returned in all exit paths, including cancellation and exception propagation.
Exceptions
- ArgumentNullException
Thrown if
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.
ComputeHash(NonCryptographicHashAlgorithm, byte[])
Computes the hash value for the specified byte array and resets the algorithm to its initial state.
public static byte[] ComputeHash(this NonCryptographicHashAlgorithm algorithm, byte[] buffer)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash value.
bufferbyte[]The byte array whose contents are appended to the algorithm.
Returns
- byte[]
A newly allocated byte array containing the computed hash value.
Remarks
This method is a one-shot computation: any pending state on algorithm is discarded before
processing. The full contents of buffer are appended, the resulting hash is retrieved, and
the algorithm is reset to its initial state on exit via
GetHashAndReset().
Exceptions
- ArgumentNullException
algorithmorbufferis null.
ComputeHash(NonCryptographicHashAlgorithm, byte[], int, int)
Computes the hash value for the specified region of a byte array and resets the algorithm to its initial state.
public static byte[] ComputeHash(this NonCryptographicHashAlgorithm algorithm, byte[] buffer, int offset, int count)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash value.
bufferbyte[]The byte array containing the region to hash.
offsetintThe zero-based offset in
bufferat which hashing begins.countintThe number of bytes to append from
buffer.
Returns
- byte[]
A newly allocated byte array containing the computed hash value.
Remarks
This method is a one-shot computation: any pending state on algorithm is discarded before
processing. Exactly count bytes from buffer, starting at
offset, are appended; the resulting hash is retrieved and the algorithm is reset to its
initial state on exit via GetHashAndReset().
Exceptions
- ArgumentNullException
algorithmorbufferis null.- ArgumentOutOfRangeException
offsetorcountis outside the bounds ofbuffer.
ComputeHash(NonCryptographicHashAlgorithm, Stream, int)
Computes the hash value for the remaining bytes of the specified stream and resets the algorithm to its initial state.
public static byte[] ComputeHash(this NonCryptographicHashAlgorithm algorithm, Stream source, int bufferSize = 4096)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash value.
sourceStreamThe stream whose bytes are read and appended to the algorithm.
bufferSizeintThe size, in bytes, of the temporary buffer used when reading from
source. The default value is 4096.
Returns
- byte[]
A newly allocated byte array containing the computed hash value.
Remarks
This method is a one-shot computation: any pending state on algorithm is discarded before
reading begins. source is read from its current position until no more bytes are available,
each block is appended to algorithm, the resulting hash is retrieved, and the algorithm is
reset to its initial state on exit via GetHashAndReset().
Exceptions
- ArgumentNullException
algorithmorsourceis null.- ArgumentOutOfRangeException
bufferSizeis less than or equal to zero.- IOException
An I/O error occurs while reading from
source.- ObjectDisposedException
sourcehas been disposed.- NotSupportedException
sourcedoes not support reading.
ComputeHash(NonCryptographicHashAlgorithm, ReadOnlySpan<byte>)
Computes the hash value for the specified span of bytes and resets the algorithm to its initial state.
public static byte[] ComputeHash(this NonCryptographicHashAlgorithm algorithm, ReadOnlySpan<byte> data)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash value.
dataReadOnlySpan<byte>The contiguous region of memory whose bytes are appended to the algorithm.
Returns
- byte[]
A newly allocated byte array containing the computed hash value.
Remarks
This method is a one-shot computation: any pending state on algorithm is discarded before
processing. The contents of data are appended, the resulting hash is retrieved, and the
algorithm is reset to its initial state on exit via
GetHashAndReset().
Exceptions
- ArgumentNullException
algorithmis null.
ComputeHashAsync(NonCryptographicHashAlgorithm, Stream, int, CancellationToken)
Asynchronously computes the hash value for the specified stream.
public static ValueTask<byte[]> ComputeHashAsync(this NonCryptographicHashAlgorithm algorithm, Stream source, int bufferSize = 81920, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe hash algorithm instance.
sourceStreamThe stream whose bytes are hashed.
bufferSizeintThe number of bytes read per iteration. Defaults to 81920.
cancellationTokenCancellationTokenA token that may be used to cancel the asynchronous read operation.
Returns
Exceptions
- ArgumentNullException
algorithmorsourceis null.- ArgumentOutOfRangeException
bufferSizeis less than or equal to zero.- OperationCanceledException
The operation was canceled.
TryVerifyHash(NonCryptographicHashAlgorithm, byte[], byte[])
Attempts to compute and verify the hash of a byte array against the expected hash value.
public static bool TryVerifyHash(this NonCryptographicHashAlgorithm algorithm, byte[] input, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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. Must not be null.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithmorexpectedHashis null.
TryVerifyHash(NonCryptographicHashAlgorithm, byte[], byte[], out bool)
Attempts to compute and verify the hash of a byte array, reporting both whether the operation succeeded and whether the hash matched.
public static bool TryVerifyHash(this NonCryptographicHashAlgorithm algorithm, byte[] input, byte[] expectedHash, out bool result)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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.
resultboolWhen this method returns true, contains true if the computed hash matched
expectedHash; otherwise, false. Always false when the method itself returns false.
Returns
- bool
true if the hash computation and comparison completed without error; false if
inputorexpectedHashis null, or an internal exception occurred.
Remarks
Unlike VerifyHash(NonCryptographicHashAlgorithm, byte[], byte[]), this overload distinguishes
between a failed operation (return value false) and a successful but non-matching comparison
(result = false). Both null inputs are treated as an
operation failure, making this overload suitable for defensive validation where inputs may be absent.
Exceptions
- ArgumentNullException
Thrown if
algorithmis null.
TryVerifyHash(NonCryptographicHashAlgorithm, byte[], string)
Attempts to compute and verify the hash of a byte array against an expected hexadecimal hash string.
public static bool TryVerifyHash(this NonCryptographicHashAlgorithm algorithm, byte[] input, string expectedHex)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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. Must not be null.
Returns
- bool
true if the computed hash matches
expectedHex; otherwise, false. Returns false ifexpectedHexis not a valid hexadecimal string.
Exceptions
- ArgumentNullException
Thrown if
algorithmorexpectedHexis null.
TryVerifyHash(NonCryptographicHashAlgorithm, Stream, byte[])
Attempts to compute and verify the hash of a stream against the expected hash value.
public static bool TryVerifyHash(this NonCryptographicHashAlgorithm algorithm, Stream stream, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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(NonCryptographicHashAlgorithm, Stream, string)
Attempts to compute and verify the hash of a stream against the expected hexadecimal hash string.
public static bool TryVerifyHash(this NonCryptographicHashAlgorithm algorithm, Stream stream, string expectedHex)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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. Must not be null.
Returns
- bool
true if the stream hash matches
expectedHex; otherwise, false. Returns false ifexpectedHexis not a valid hexadecimal string.
Exceptions
- ArgumentNullException
Thrown if
algorithmorexpectedHexis null.
TryVerifyHash(NonCryptographicHashAlgorithm, ReadOnlyMemory<byte>, byte[])
Attempts to compute and verify the hash of a memory buffer against the expected hash value.
public static bool TryVerifyHash(this NonCryptographicHashAlgorithm algorithm, ReadOnlyMemory<byte> input, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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. Must not be null.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithmorexpectedHashis null.
TryVerifyHash(NonCryptographicHashAlgorithm, 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 NonCryptographicHashAlgorithm algorithm, ReadOnlySpan<byte> input, ReadOnlySpan<byte> expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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(NonCryptographicHashAlgorithm, string, Encoding, byte[])
Attempts to compute and verify the hash of an encoded string against the expected hash value.
public static bool TryVerifyHash(this NonCryptographicHashAlgorithm algorithm, string input, Encoding encoding, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash. Must not be null.
inputstringThe plain-text string to encode and hash. Must not be null.
encodingEncodingThe encoding used to convert
inputto bytes. Must not be null.expectedHashbyte[]The expected hash value as a byte array. Must not be null.
Returns
Exceptions
- ArgumentNullException
Thrown if
algorithm,input,encoding, orexpectedHashis null.
TryVerifyHashAsync(NonCryptographicHashAlgorithm, byte[], byte[], CancellationToken)
Attempts to asynchronously compute and verify the hash of a byte array against the expected hash value.
public static Task<bool> TryVerifyHashAsync(this NonCryptographicHashAlgorithm algorithm, byte[] input, byte[] expectedHash, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input data to hash. Must not be null.
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 matches
expectedHash; otherwise, false.
Remarks
input is wrapped in a non-allocating MemoryStream and passed to the
stream-based VerifyHashAsync(NonCryptographicHashAlgorithm, Stream, byte[], CancellationToken)
overload.
Exceptions
- ArgumentNullException
Thrown if
algorithm,input, orexpectedHashis null.
TryVerifyHashAsync(NonCryptographicHashAlgorithm, byte[], string, CancellationToken)
Attempts to asynchronously compute and verify the hash of a byte array against the expected hexadecimal hash string.
public static Task<bool> TryVerifyHashAsync(this NonCryptographicHashAlgorithm algorithm, byte[] input, string expectedHex, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash. Must not be null.
inputbyte[]The input data to hash. Must not be null.
expectedHexstringThe expected hash as a hexadecimal string. 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
input is wrapped in a non-allocating MemoryStream and passed to the
stream-based VerifyHashAsync(NonCryptographicHashAlgorithm, Stream, string, CancellationToken)
overload.
Exceptions
- ArgumentNullException
Thrown if
algorithm,input, orexpectedHexis null.
TryVerifyHashAsync(NonCryptographicHashAlgorithm, 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 NonCryptographicHashAlgorithm algorithm, Stream stream, byte[] expectedHash, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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(NonCryptographicHashAlgorithm, 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 NonCryptographicHashAlgorithm algorithm, Stream stream, ReadOnlyMemory<byte> expectedHash, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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(NonCryptographicHashAlgorithm, 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 NonCryptographicHashAlgorithm algorithm, Stream stream, string expectedHex, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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. 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.
Exceptions
- ArgumentNullException
Thrown if
algorithmorexpectedHexis null.
TryVerifyHashAsync(NonCryptographicHashAlgorithm, string, Encoding, byte[], CancellationToken)
Attempts to asynchronously compute and verify the hash of an encoded string against the expected hash value.
public static Task<bool> TryVerifyHashAsync(this NonCryptographicHashAlgorithm algorithm, string input, Encoding encoding, byte[] expectedHash, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm instance used to compute the hash. Must not be null.
inputstringThe input string to encode and hash. Must not be null.
encodingEncodingThe character encoding used to convert
inputto bytes. Must not be null.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 matches
expectedHash; otherwise, false.
Remarks
The encoded bytes are wrapped in a non-allocating MemoryStream and passed to the stream-based VerifyHashAsync(NonCryptographicHashAlgorithm, Stream, byte[], CancellationToken) overload.
Exceptions
- ArgumentNullException
Thrown if
algorithm,input,encoding, orexpectedHashis null.
VerifyHash(NonCryptographicHashAlgorithm, byte[], byte[])
Verifies that the computed hash of the input data matches the expected hash value.
public static bool VerifyHash(this NonCryptographicHashAlgorithm algorithm, byte[] input, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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
The algorithm state is reset before computation and restored to a clean state after GetHashAndReset() completes. Any prior incremental state is discarded.
Exceptions
- ArgumentNullException
Thrown if
algorithm,input, orexpectedHashis null.
VerifyHash(NonCryptographicHashAlgorithm, 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 NonCryptographicHashAlgorithm algorithm, byte[] input, string expectedHex)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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 the hash is computed so that a malformed hex string
fails fast without performing unnecessary work.
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(NonCryptographicHashAlgorithm, Stream, byte[])
Verifies that the computed hash of the stream matches the expected hash value.
public static bool VerifyHash(this NonCryptographicHashAlgorithm algorithm, Stream stream, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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
The algorithm state is reset before the stream is read. Any prior incremental state is discarded.
Exceptions
- ArgumentNullException
Thrown if
algorithm,stream, orexpectedHashis null.
VerifyHash(NonCryptographicHashAlgorithm, 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 NonCryptographicHashAlgorithm algorithm, Stream stream, string expectedHex)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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 the stream is read so that a malformed hex string
fails fast without consuming stream data or wasting the hash computation.
A malformed expectedHex string is treated as a non-match and returns
false.
Exceptions
- ArgumentNullException
Thrown if
algorithm,stream, orexpectedHexis null.
VerifyHash(NonCryptographicHashAlgorithm, ReadOnlyMemory<byte>, byte[])
Verifies that the computed hash of the input memory block matches the expected hash value.
public static bool VerifyHash(this NonCryptographicHashAlgorithm algorithm, ReadOnlyMemory<byte> input, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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(NonCryptographicHashAlgorithm, ReadOnlySpan<byte>, ReadOnlySpan<byte>) overload.
Exceptions
- ArgumentNullException
Thrown if
algorithmorexpectedHashis null.
VerifyHash(NonCryptographicHashAlgorithm, ReadOnlySpan<byte>, ReadOnlySpan<byte>)
Verifies that the computed hash of the input span matches the expected hash span.
public static bool VerifyHash(this NonCryptographicHashAlgorithm algorithm, ReadOnlySpan<byte> input, ReadOnlySpan<byte> expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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
The algorithm state is reset before computation and restored to a clean state via GetHashAndReset() after the digest is produced.
Exceptions
- ArgumentNullException
Thrown if
algorithmis null.
VerifyHash(NonCryptographicHashAlgorithm, string, Encoding, byte[])
Verifies that the computed hash of the encoded string matches the expected hash value.
public static bool VerifyHash(this NonCryptographicHashAlgorithm algorithm, string text, Encoding encoding, byte[] expectedHash)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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
Non-cryptographic hash algorithms are designed for scenarios such as checksums, hash tables, sharding, bucketing, fingerprinting, and accidental-corruption detection. They must not be used for password hashing, digital signatures, message authentication, tamper detection, or other security-sensitive purposes.
Exceptions
- ArgumentNullException
Thrown if
algorithm,text,encoding, orexpectedHashis null.
VerifyHashAsync(NonCryptographicHashAlgorithm, Stream, byte[], CancellationToken)
Asynchronously verifies that the computed hash of a stream matches the expected hash value.
public static Task<bool> VerifyHashAsync(this NonCryptographicHashAlgorithm algorithm, Stream stream, byte[] expectedHash, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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
The algorithm state is reset before the stream is read. Any prior incremental state is discarded.
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.- OperationCanceledException
cancellationTokenwas signaled before or during stream reading.
VerifyHashAsync(NonCryptographicHashAlgorithm, 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 NonCryptographicHashAlgorithm algorithm, Stream stream, ReadOnlyMemory<byte> expectedHash, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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.
If cancellationToken is already canceled on entry, an
OperationCanceledException is thrown immediately before any I/O begins.
Exceptions
- ArgumentNullException
Thrown if
algorithmorstreamis null.- OperationCanceledException
cancellationTokenwas signaled before or during stream reading.
VerifyHashAsync(NonCryptographicHashAlgorithm, Stream, string, CancellationToken)
Asynchronously verifies that the computed hash of a stream matches the expected hexadecimal hash string.
public static Task<bool> VerifyHashAsync(this NonCryptographicHashAlgorithm algorithm, Stream stream, string expectedHex, CancellationToken cancellationToken = default)
Parameters
algorithmNonCryptographicHashAlgorithmThe NonCryptographicHashAlgorithm 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 the stream is read so that a malformed hex string
fails fast without consuming stream data. 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.- OperationCanceledException
cancellationTokenwas signaled before or during stream reading.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |