C# – How to Create an MD5 Hash

MD5 hashes are useful for when you need a string of characters that will always be generated given the same input. MD5 hashes are used to uniquely identify files based on their contents and they have also been used to store passwords in an “encrypted” format.

A word of caution on using MD5 hashing to store passwords in a database is that there exists searchable online databases of strings to MD5 hash mapping which allow someone to do a reverse lookup of what a password is by looking up the MD5 hash to plain text password mapping. So if you are relying solely on a straight MD5 hashing to store you password in a database you may want to consider doing something else such as applying a salt to the resultant hash string before you store it in the database.

Here is sample C# code to generate an MD5 hash from a string:

string password = "foo";
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
   s.Append(b.ToString("x2").ToLower());
}
password = s.ToString();

MD5 Algorithm