How do I calculate a MD5 hash from a string?

Published 09 October 06 11:15 AM

It is a common practice to store passwords in databases using a hash. MD5 (defined in RFC 1321) is a common hash algorithm, and using it from C# is easy.

Here’s an implementation of a method that converts a string to an MD5 hash, which is a 32-character string of hexadecimal numbers.

public string CalculateMD5Hash(string input)
{
    // step 1, calculate MD5 hash from input
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);
 
    // step 2, convert byte array to hex string
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hash.Length; i++)
    {
        sb.Append(hash[i].ToString("X2"));
    }
    return sb.ToString();
}

An example call:

string hash = CalculateMD5Hash("abcdefghijklmnopqrstuvwxyz");

…returns a string like this:

C3FCD3D76192E4007DFB496CCA67E13B

To make the hex string use lower-case letters instead of upper-case, replace the single line inside the for loop with this line:

sb.Append(hash[i].ToString("x2"));

The difference is the ToString method parameter.

[author: Jani Järvinen, C# MVP]

Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# bazile said on October 10, 2006 3:04 AM:

Also you can use FormsAuthentication.HashPasswordForStoringInConfigFile(string, "MD5"), The class is located in System.Web.Security namespace.

# Charlie Calvert's Community Blog said on October 15, 2006 7:05 PM:

The team needs your help debugging the new Visual Studio 2005 Service Pack 1 Beta . I've written about

# Jon Galloway said on September 24, 2007 2:29 AM:

Summary Gravatar (Globally Recognized Avatar) provides a simple way to add avatars to community based

# Steve said on November 3, 2009 10:55 AM:

Hey, I have an algorithm from way back written in vb6.  It is so kewl that your algorithm creates the same MD5 hash (in other words, your algorithm is reliable and in line with the rfc ;-)

Tks for the code.

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker