Skip to content

Instantly share code, notes, and snippets.

@sebnilsson
Created December 30, 2017 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebnilsson/e12a96cd07e5b044eea7bc8b7477b20d to your computer and use it in GitHub Desktop.
Save sebnilsson/e12a96cd07e5b044eea7bc8b7477b20d to your computer and use it in GitHub Desktop.
Compute hash in .NET using async await
public static class HashAlgorithmExtensions
{
private const int BufferSize = 4096;
public static async Task<byte[]> ComputeHashAsync(this HashAlgorithm hash, Stream inputStream)
{
if (hash == null) throw new ArgumentNullException(nameof(hash));
if (inputStream == null) throw new ArgumentNullException(nameof(inputStream));
hash.Initialize();
var buffer = new byte[BufferSize];
var streamLength = inputStream.Length;
while (true)
{
var read = await inputStream.ReadAsync(buffer, 0, BufferSize).ConfigureAwait(false);
if (inputStream.Position == streamLength)
{
hash.TransformFinalBlock(buffer, 0, read);
break;
}
hash.TransformBlock(buffer, 0, read, default(byte[]), default(int));
}
return hash.Hash;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment