StephenCleary / HashAlgorithms

CRC calculation for .NET
MIT License
24 stars 4 forks source link

Logo

HashAlgorithms Build status codecov NuGet version API docs

Hash algorithm implementations for .NET, including CRC (CRC32 and CRC16).

All hash algorithms support streaming (hashing a block at a time) and have full support for Span<T> to prevent unnecessary memory allocation. They also have excellent downlevel platform support (netstandard1.3).

CRC32

CRC32 is a generic 32-bit CRC implementation, patterned after Boost's CRC library.

Creating a CRC32

You can pass a CRC32.Definition instance into the constructor to control all the CRC algorithm parameters.

var defaultHasher = new CRC32(); // uses CRC32.Definition.Default
var bzipHasher = new CRC32(CRC32.Definition.BZip2);
var customHasher = new CRC32(new CRC32.Definition
{
    TruncatedPolynomial = 0x1EDC6F41,
    Initializer = 0xFFFFFFFF,
    FinalXorValue = 0xFFFFFFFF,
    ReverseDataBytes = true,
    ReverseResultBeforeFinalXor = true,
});

Once created, the CRC32 instance can be used like any other HashAlgorithm instance.

Implementations

Built-in implementations include:

CRC16

CRC16 is a generic 16-bit CRC implementation, patterned after Boost's CRC library.

Creating a CRC16

You can pass a CRC16.Definition instance into the constructor to control all the CRC algorithm parameters.

var defaultHasher = new CRC16(); // uses CRC16.Definition.Default
var ccittHasher = new CRC16(CRC16.Definition.Ccitt);
var customHasher = new CRC16(new CRC16.Definition
{
    TruncatedPolynomial = 0x1021,
    Initializer = 0xFFFF,
    FinalXorValue = 0xFFFF,
    ReverseDataBytes = true,
    ReverseResultBeforeFinalXor = true,
});

Once created, the CRC16 instance can be used like any other HashAlgorithm instance.

Implementations

Built-in implementations include:

HashAlgorithmBase

The Nito.HashAlgorithm.Core NuGet library has a HashAlgorithmBase type that provides an easier way to define hash algorithms across the widest possible number of platforms (netstandard1.3 - netstandard2.1). It pulls in System.Memory on platforms that require it to provide support for Span<T>.

To use HashAlgorithmBase, your hash algorithm implementation should pass the size of the hash (in bits) to the HashAlgorithmBase constructor. HashAlgorithmBase will set HashSizeValue or override HashSize appropriately, depending on platform.

Then implement these two methods:

protected void DoHashCore(ReadOnlySpan<byte> source);
protected void DoHashFinal(Span<byte> destination);

The DoHashCore method should hash the bytes in source. The DoHashFinal method should save the hash result into destination (hint: BinaryPrimitives is useful when implementing this method).

That's it; the HashAlgorithmBase takes care of implementing the HashAlgorithm methods, including overrides for efficient Span<T>-based hashing.