o nebi, zemi a všetkom medzi tým

Calculating hash while processing stream

Recently I needed to calculate hash of a unspecified Stream while I was processing its data. Along the way I discovered 3 additional methods to calculate hash – all suitable when you can’t rely on seeking in the stream.

The direct approach

This is the direct approach to calculate hash from data in stream, but its setback is that after calculating the hash value the stream is read to the end. If the source stream was seekable (FileStream, MemoryStream…), you can just seek back and process the stream normally, but what if you can’t seek in the processing stream?

The block approach

You can calculate the hash on the go, using TransformBlock and TransformFinalBlock methods of MD5 class (or any other class implementing ICryptoTransform).

As you can see, you can enclose the hash processing into CryptoStream, which is calculating the hash value during reading of the stream, which results in cleaner code.

Note – do not use CryptoStream.FlushFinalBlock() while using CryptoStreamMode.Read, because the CryptoStream itself can tell that the source stream reached its end and called this method already.

The nice approach – CryptoStream scenario #2

The scenario #1 is useful when you have a single source stream, but when you want to calculate hash value of output of your algorighm and do not have input in form of a stream, you can use CryptoStreamMode.Write.