C#: MD5 Hash Method

I needed to create an MD5 hash of a string today that could be sent along with a web service request to a third party application. I’ve never done this before using .NET but it was exteremely simple! Here is the code:

/// <summary>
/// Gets the MD5 hash value for the passed in value parameter
/// </summary>
/// <param name="value">The string value to hash</param>
/// <param name="upperCase">Indicates whether or not the return value should be upper case</param>
/// <returns>The MD5 hash of the value parameter</returns>
public static string GetMD5Hash(string value, bool upperCase)
    // Instantiate new MD5 Service Provider to perform the hash
    System.Security.Cryptography.MD5CryptoServiceProvider md5ServiceProdivder = new System.Security.Cryptography.MD5CryptoServiceProvider();
     // Get a byte array representing the value to be hashed and hash it
    byte[] data = System.Text.Encoding.ASCII.GetBytes(value);
    data = md5ServiceProdivder.ComputeHash(data);

    // Get the hashed string value
    StringBuilder hashedValue = new StringBuilder();
    for (int i = 0; i < data.Length; i++)

    // Return the string in all caps if desired
    if (upperCase)
        return hashedValue.ToString().ToUpper();

    return hashedValue.ToString();

4 Responses to “C#: MD5 Hash Method”

  1. MD5 Hash Generator Says:

    Nice touch adding the option to make it uppercase.

  2. Janus Says:

    There is an easier way 🙂

    Instead of the for-loop, just do:

    hashedValue = BitConverter.ToString(data).Replace(“-“, “”);

    • Nick Olsen Says:

      Thanks for the tip! The only thing I would mention is that using that method, you will always be returned an upper case string. My original implementation allowed for lower or upper case hash strings.

  3. Antonio Musarra Says:

    Hello Nick,
    Your method I have been very useful to create a SOAP client SugarCRM. The code I also added the source.

    Antonio M (http://musarra.wordpress.com).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: