For security purpose, passwords are encrypted using a hash and then stored in databases or in xml files. MD5 is a very common hash algorithm and it is very easy to use it from C#. Hash code is basically a 32-character string of hexadecimal numbers.

.Net Framework class library contains a class “MD5” which is used to create hash code based on the MD5 hash algorithm. This class “MD5” can be found in the “System.Security.Cryptography” namespace.Following implementation of a method can be used to convert string to an MD5 hash code:

public static  string CalculateMD5Hash(string strInput)
{
  MD5 md5 = System.Security.Cryptography.MD5.Create();
  byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strInput);
  byte[] hash = md5.ComputeHash(inputBytes);            

 
StringBuilder sb = new StringBuilder();
           
 
for (int i = 0; i < hash.Length; i++)
           
 
{
               
   
sb.Append(hash[i].ToString("x2"));
 
 
}
         
 
return sb.ToString();
       
}

An example call of the above method:

string strHashCode = CalculateMD5Hash("abcdefgh");

the variable “strHashCode” will receive a hash code as below:

a8dc4081b13434b45189a720b77b6818