Converting a md5 hash byte array to a string

Blankman picture Blankman · Mar 12, 2010 · Viewed 77.9k times · Source

How can I convert the hashed result, which is a byte array, to a string?

byte[] bytePassword = Encoding.UTF8.GetBytes(password);

using (MD5 md5 = MD5.Create())
{
    byte[] byteHashedPassword = md5.ComputeHash(bytePassword);
} 

I need to convert byteHashedPassword to a string.

Answer

Philippe Leybaert picture Philippe Leybaert · Mar 12, 2010
   public static string ToHex(this byte[] bytes, bool upperCase)
    {
        StringBuilder result = new StringBuilder(bytes.Length*2);

        for (int i = 0; i < bytes.Length; i++)
            result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));

        return result.ToString();
    }

You can then call it as an extension method:

string hexString = byteArray.ToHex(false);