What is the best solution in C# for computing an "on the fly" md5 like hash of a stream of unknown length? Specifically, I want to compute a hash from data received over the network. I know I am done receiving data when the sender terminates the connection, so I don't know the length in advance.
[EDIT] - Right now I am using md5, but this requires a second pass over the data after it's been saved and written to disk. I'd rather hash it in place as it comes in from the network.
Further to @peter-mourfield 's answer, here is the code that uses
ComputeHash()
:Since both the stream as well as MD5 implement IDisposible, you need to use
using(...){...}
The method in the code example returns the same string that is used for the MD5 checksum in Azure Blob Storage.
MD5, like other hash functions, does not require two passes.
To start:
As each block of data arrives:
To finish and retrieve the hash:
This pattern works for any type derived from
HashAlgorithm
, includingMD5CryptoServiceProvider
andSHA1Managed
.HashAlgorithm
also defines a methodComputeHash
which takes aStream
object; however, this method will block the thread until the stream is consumed. Using theTransformBlock
approach allows an "asynchronous hash" that is computed as data arrives without using up a thread.Necromancing.
Two possibilitites in C# .NET Core:
or with BouncyCastle:
The System.Security.Cryptography.MD5 class contains a ComputeHash method that takes either a byte[] or Stream. Check it out at http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5_members.aspx