Last active
April 24, 2018 20:54
-
-
Save mjs3339/fa7ce02398aa67ffc7c6903ae4d2135f to your computer and use it in GitHub Desktop.
C# FNV1a 512Bit Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FNV1a512 : HashAlgorithm | |
{ | |
private readonly BigInteger _K = "35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759".NewBigInteger10(); | |
private BigInteger _hash; | |
private readonly BigInteger Seed = "9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785".NewBigInteger10(); | |
public FNV1a512() | |
{ | |
_hash = Seed; | |
} | |
public FNV1a512(string seed) | |
{ | |
Seed = seed.NewBigInteger10(); | |
_hash = Seed; | |
} | |
public override int HashSize => 512; | |
public override void Initialize() | |
{ | |
_hash = Seed; | |
} | |
protected override void HashCore(byte[] bytes, int ibStart, int cbSize) | |
{ | |
Hash(bytes, ibStart, cbSize); | |
} | |
private void Hash(byte[] bytes, int ibStart, int cbSize) | |
{ | |
if (bytes == null) | |
return; | |
if (ibStart >= bytes.Length || cbSize > bytes.Length) | |
return; | |
var p = 0; | |
while (cbSize > 0) | |
{ | |
_hash ^= bytes[p + ibStart]; | |
_hash *= _K; | |
cbSize--; | |
p++; | |
} | |
_hash = _hash ^ (_hash >> 256); | |
} | |
/// <summary> | |
/// BigInteger does not overflow, so we limit the output to 512Bits. | |
/// </summary> | |
protected override byte[] HashFinal() | |
{ | |
return _hash.ToByteArray().SubByte(0, 64); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment