Hashing

Purpose

BLAKE2b is a cryptographic hash function. It takes a message of any size and produces a 128-bit to 512-bit hash.

This hash acts as a fingerprint for the data. Hashes can be used to uniquely identify messages, detect corruption, detect duplicate data, and index data in a hash table.

However, unkeyed hashes do not provide authentication (e.g. for Encrypt-then-MAC). Furthermore, they should be avoided for key derivation. Use the linked APIs instead.

Usage

ComputeHash

Fills a span with a hash computed from a message.

BLAKE2b.ComputeHash(Span<byte> hash, ReadOnlySpan<byte> message)

Exceptions

ArgumentOutOfRangeException

hash has a length less than MinHashSize or greater than MaxHashSize.

CryptographicException

The hash could not be computed.

ComputeHash

Fills a span with a hash computed from a Stream message. This is useful for hashing files.

BLAKE2b.ComputeHash(Span<byte> hash, Stream message)

Exceptions

ArgumentOutOfRangeException

hash has a length less than MinHashSize or greater than MaxHashSize.

ArgumentNullException

message is null.

InvalidOperationException

message cannot be read.

CryptographicException

The hash could not be computed.

IncrementalBLAKE2b

Provides support for computing a hash from several messages.

using var blake2b = new IncrementalBLAKE2b(int hashSize);
blake2b.Update(ReadOnlySpan<byte> message1);
blake2b.Update(ReadOnlySpan<byte> message2);
blake2b.Finalize(Span<byte> hash1);

// Avoid another using statement
blake2b.Reinitialize(int hashSize);
blake2b.Update(ReadOnlySpan<byte> message3);
// Cache the state
blake2b.CacheState();
blake2b.Finalize(Span<byte> hash2);

// Restore the cached state
blake2b.RestoreCachedState();
// hash3 == hash2
blake2b.Finalize(Span<byte> hash3);

Exceptions

ArgumentOutOfRangeException

hashSize is less than MinHashSize or greater than MaxHashSize.

ArgumentOutOfRangeException

hash has a length not equal to hashSize.

CryptographicException

The hash could not be computed.

InvalidOperationException

Cannot update after finalizing or finalize twice (without reinitializing or restoring a cached state).

InvalidOperationException

Cannot cache the state after finalizing (without reinitializing).

InvalidOperationException

Cannot restore the state when it has not been cached.

ObjectDisposedException

The object has been disposed.

Constants

These are used for validation and/or save you defining your own constants.

public const int HashSize = 32;
public const int MinHashSize = 16;
public const int MaxHashSize = 64;

Notes

The security level of BLAKE2b is 1/2 the output length (e.g. 128-bit security for a 256-bit hash).​

Last updated