Created
December 30, 2017 20:54
-
-
Save sebnilsson/e12a96cd07e5b044eea7bc8b7477b20d to your computer and use it in GitHub Desktop.
Compute hash in .NET using async await
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 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