Thursday, September 6, 2012

Calculate MD5 Hash of a String

In today's post I want to present, how to calculate the MD5 hash of a string using C#.
First a little basics about hashing in general:
A hash function is a function, which creates from a input of arbitrary length an output of fixed length. The function should one the one hand be not or hardly invertible, meaning given the output, calculating the corresponding input needs to be hard.
On the other hand the function should create only a few collisions, meaning, different inputs should create different outputs, furthermore little changes to the input should create big changes in the output.

Why all that?
One example is the storage of passwords on a webserver. The passwords are not saved in plain text but hashed. So on the one hand the administrator cannot see the passwords of his clients, since he cannot inverse the hash value, and on the other hand of course intruders cannot do so also.
Another example is the hash sum calculation of files, for example to verify the correct transfer. Comparing the 2 files in total would need too many ressources, so you compare the hash sums. Are these equivalent, the files are identical with a high probablity since there are little hash collisions, if already a small part of the file is different, the hash value is probably totally different.

Now to the code. With using System.Security.Cryptography the following code calculates the hash value of a string:

MD5 Md5Hash = MD5.Create();
byte[] Data = Md5Hash.ComputeHash(Encoding.Default.GetBytes("Zu hashende Zeichenkette"));
string Hash =  System.BitConverter.ToString(Data);

The first line creates a MD5 object. In the second line the string is hashed with MD5 and the hash is returned as a byte array. The function ToString() in the third line of the BitConverter then converts this array to a hexadecimal string, which is mostly used to represent hash values.

No comments:

Post a Comment