There are a few instances in which you’ll need to hash a combination of data. You might resort to creating one big string and hashing that. It has a clear disadvantage from a memory and processing point of few. It might even be impractical when files or streams are involved. That’s why I created a BlockHasher utility class that helps to generate¬†these types of hashes.

HashAlgorithm

.Net offers the following through the HashAlgorithm class:

  • TransformBlock based on a buffer (byte array)
  • TransformFinalBlock that creates the hash (also a byte array)
  • ComputeHash(stream) – great for streams, but this method is not usable for async operations because it will block the tread until the stream has been read and it does not work together with the transform methods.

Wanted: more features

Basically you want the following features in this scenario:

  • Transformation of a stream
  • Transformation of a buffer / byte array (already present, but you might want a simpler version)
  • Transformation of a string – with optional encoding
  • Async stream transformation support!

To make things more readable, you might want to return the hash as a hexadecimal string or – a shorter and but less frequently¬†used¬†–¬†base64 string. I find myself always using the same lines of code, so I decided to add it to the class.

BlockHasher

Without further ado, let’s see¬†the class:

API Signature Hashing

Lots of API’s use a HMAC SHA1 signature¬†to authenticate messages. I’ve created some example code on how the BlockHasher can be used to generate the signature:

Async stream hashing

Hashing big files using async streams is pretty easy:

Wrap up

So that’s it. Be sure to visit the class on GitHub if you think it should be changed / expanded.