Skip to content

Commit

Permalink
refactor: use incremental hasher
Browse files Browse the repository at this point in the history
Signed-off-by: Alan Brault <alan.brault@visus.io>
  • Loading branch information
xaevik committed Oct 24, 2023
1 parent b1f15d6 commit e83fb77
Showing 1 changed file with 6 additions and 13 deletions.
19 changes: 6 additions & 13 deletions src/cuid.net/Cuid2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,26 +110,19 @@ public override int GetHashCode()
public override string ToString()
{
Span<byte> buffer = stackalloc byte[16];
Span<byte> result = stackalloc byte[64];

BinaryPrimitives.WriteInt64LittleEndian(buffer[..8], _timestamp);
BinaryPrimitives.WriteUInt64LittleEndian(buffer[^8..], _counter);

byte[] data = new byte[buffer.Length + _fingerprint.Length + _random.Length];
IncrementalHash.Initialize(HashAlgorithm.Sha512, out IncrementalHash state);

Buffer.BlockCopy(buffer.ToArray(), 0, data, 0, buffer.Length);
Buffer.BlockCopy(_fingerprint, 0, data, buffer.Length, _fingerprint.Length);
Buffer.BlockCopy(_random, 0, data, buffer.Length + _fingerprint.Length, _random.Length);

Sha512 sha512 = new();
IncrementalHash.Update(ref state, buffer);
IncrementalHash.Update(ref state, _fingerprint);
IncrementalHash.Update(ref state, _random);

sha512.Hash(data, result);
if ( !sha512.Verify(data, result) )
{
return string.Empty;
}
byte[] hash = IncrementalHash.Finalize(ref state);

return _prefix + Utils.Encode(result)[..( _maxLength - 1 )];
return _prefix + Utils.Encode(hash)[..( _maxLength - 1 )];
}

private static class Context
Expand Down

0 comments on commit e83fb77

Please sign in to comment.