FNV1a128b.cs

FNV1a Patterned 128Bit Hashing Algorithm using BigInteger

using System.Numerics;
using System.Security.Cryptography;
public class FNV1a128b : HashAlgorithm
{
    private readonly BigInteger K = "309485009821345068724781371".BigIntegerBase10();
    private readonly BigInteger M = "340282366920938463463374607431768211456".BigIntegerBase10();
    private          BigInteger _hash;
    private readonly BigInteger Seed = "144066263297769815596495629667062367629".BigIntegerBase10();
    public FNV1a128b()
    {
        _hash = Seed;
    }
    public FNV1a128b(BigInteger seed)
    {
        Seed  = seed;
        _hash = Seed;
    }
    public override int HashSize => 128;
    public override void Initialize()
    {
        _hash = Seed;
    }
    protected override void HashCore(byte[] bytes, int ibStart, int cbSize)
    {
        Hash128(bytes, ibStart, cbSize);
    }
    protected override byte[] HashFinal()
    {
        return _hash.ToByteArray();
    }
    private unsafe void Hash128(byte[] bytes, int ibStart, int cbSize)
    {
        fixed (byte* pb = bytes)
        {
            var np = pb + ibStart;
            for (; cbSize > 0; --cbSize, np++)
                _hash = ((_hash ^ *np) * K) % M;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *