Hash Values

In this part we are going to learn how to ensure that data coming to you has not been tampered with during the transfer. The technique that we will be using is hash. Hash values allow us to verify the integrity of data. The hash value of received data can be compared to the hash value of data that was sent to check if the data is tampered.

.NET Framework classes for creating hashes

.NET Framework provides following main classes to work with hashes:

  • SHA1Managed
  • MD5CryptoServiceProvider
  • MACTripleDES

Since SHA1 is now a broken algorithm, we will use MD5CryptoServiceProvider to generate hash values.

Example
We are going to create a helper class that will help us create and verify hash values using MD5 algorithm. The class contains two methods – GetHash() and VerifyHash(). The former accepts string whose hash value is to be generated and returns the computed hash as a byte array. The later accepts the message as it was received and the hash generated previously and returns true if the message is not altered during transmit otherwise returns false.

MD5HashHelper.cs

Let’s dissect the code step by step:

  1. We first need to import System.Security.Cryptography namespace in your class
  2. The GetHash() accepts string whose hash value is to be generated and returns the computed hash as a byte array.
  3. Inside the function we used UTF8Encoding class and get a byte representation of the string to be transferred.
  4. We then create an instance of MD5CryptoServiceProvider class and call it’s ComputeHash by passing the byte created above to it.
  5. The ComputeHash() function generates the hash for the given data and returns another byte array that represents the hash value of the data.
  6. The VerifyHash() function accepts the message as it was received and the hash generated previously and returns true if the message is not altered during transmit otherwise returns false.
  7. Inside this function we again use UTF8Encoding class and generate byte representation of the received message.
  8. We then compute hash for this data using the same ComputeHash() method of MD5CryptoServiceProvider class.
  9. Finally, we run a for loop and check each and every byte of original hash value and the hash we generated above. If both the hash values are matching we can conclude that the data is not tampered.

Check http://www.dotnetbips.com for original articles.