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++)
        hashedValue.Append(data[i].ToString("x2"));

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

    return hashedValue.ToString();
}
Follow

Get every new post delivered to your Inbox.

Join 69 other followers