Search code examples
c#hashcryptographymd5cryptographic-hash-function

Converting a md5 hash byte array to a string


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.


Solution

  •    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);