private static string HashValue(ReadOnlySpan <char> value, uint length, Span <byte> bufferSpan) { using var hashAlgorithm = SHA256.Create(); Encoding.ASCII.GetBytes(value, bufferSpan); // Hashed output maxes out at 32 bytes @ 256bit/8 so we're safe to use stackalloc Span <byte> hash = stackalloc byte[32]; hashAlgorithm.TryComputeHash(bufferSpan, hash, out int _); // Length maxes out at 64 since we throw if options is greater return(HexEncoder.Encode(hash.Slice(0, (int)(length / 2)))); }
/// <inheritdoc/> public string Create(string value, uint length) { int len = (int)length; int byteCount = Encoding.ASCII.GetByteCount(value); using (var hashAlgorithm = SHA256.Create()) using (IManagedByteBuffer buffer = this.memoryAllocator.AllocateManagedByteBuffer(byteCount)) { Encoding.ASCII.GetBytes(value, 0, byteCount, buffer.Array, 0); byte[] hash = hashAlgorithm.ComputeHash(buffer.Array, 0, byteCount); return($"{HexEncoder.Encode(new Span<byte>(hash).Slice(0, len / 2))}"); } }