How do I calculate a MD5 hash from a string?

How do I calculate a MD5 hash from a string?

Rate This
  • Comments 20

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]

Leave a Comment
  • Please add 5 and 6 and type the answer here:
  • Post
  • Also you can use FormsAuthentication.HashPasswordForStoringInConfigFile(string, "MD5"), The class is located in System.Web.Security namespace.

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

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

  • 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.

  • You shouldn't be converting to ASCII as this loses information. In fact, any of the other currently existing encodings from System.Text.Encoding would have been fine.

  • I have to agree with Rik, suggesting ASCII decoding is not what I would expect from CSharpFAQ. Also noting that MD5 is not the securest choice would not hurt.

  • can someone please decrypt for me 44edff8f24d01ed30f591f0a1fb6890d

    and email me @ crosby.samantha@gmail.com when you have the results

  • Hi Samantha,

    I decrypted 44edff8f24d01ed30f591f0a1fb6890d and it says:

    "Are you really that stupid Samantha? Seriously – do us all a favor and unplug your computer now! You are so stupid, that you try to drown fish. You are so dumb, blondes tell jokes about you."

  • @Samanthabluestar702

    Ive tryed to reverse hash it but found nothing;

    @***

    isc.sans.edu/.../reversehash.html

    you dumb ass...

  • You should ===ALWAYS=== salt hashes by appending an arbitrary string to the input. MD5 has long been considered broken; consider using alternatives like RIPEMD-160 or SHA512 if possible.

    See:

    System.Security.Cryptography.RIPEMD160Managed

    and

    System.Security.Cryptography.SHA512Managed

    In this day and age it's trivial to break unsalted MD5 hashes in minutes, using CUDA GPGPUs.

    Sam's hash 44edff8f24d01ed30f591f0a1fb6890d seems to be either nontrivial, salted or cryptographically strong.

  • could you tell me what it means?

    16e68521ce378acce7e8e4f72e9270c7

    thank you! please help me, it's important for me!

  • this is a joke. i am looking for the actual md5 algorithm.

  • This will not work with international characters, you should switch from ASCII to UTF8, by changing "Encoding.ASCII" to "Encoding.UTF8" -- for English characters, all values, byte for byte will be the same, but for instance if your user has Japanese Kanji or Chinese characters (or anything else) in their password, this will not work.

    Secondly, you MUST use a sufficiently long salt (look it up) if you're going to use a function like this for cryptographic purposes (i.e. storing password hashes in a database), otherwise this algorithm is NOT secure and anybody with a rainbow table can crack your passwords (once they hack your server and leak your database -- this happens all the time).

  • Blog de programacion

    http://insanedev.blogspot.mx/

  • Few points:

    0. Don't use MD5 (or use it in simple cases where you don't want pure strings to show, and no reverse action is required)

    1. Put MD5.Create in using (AFAIK there is a private implementation of IDisposable)

    2. Promote encoding to parameters, and make overload that uses Encoding.Default (or Encoding.Unicode, or any you want to be default)

    3. Guid is 128 bit wide same as MD5 hash. It may give you little more control if you return Guid from such a method

    4. Such things go nice alongside with Extension methods (no null checks, and empty string is valid):

    public static class StringExtensions

       {

           public static Guid Md5(this String item)

           {

               return item.Md5(Encoding.Default);

           }

           public static Guid Md5(this String item, Encoding encoding)

           {

               using (var md5 = MD5.Create())

               {

                   return new Guid(md5.ComputeHash(encoding.GetBytes(item)));

               }

           }

       }

Page 1 of 2 (20 items) 12