95

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.

1
  • 1
    MD5 is deprecated. It is inherently broken as it does not reach the standards of collision or preimage resistance. For passwords, it's better to use iterated key-derivation functions such as Argon2 or PDKDF2. Commented Apr 16, 2021 at 7:54

9 Answers 9

91
   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);
Sign up to request clarification or add additional context in comments.

8 Comments

what is the significance of upper casing?
a matter of preference. That's why I added a parameter to my method, so the caller can choose
No need to reinvent the wheel when you already have Convert.ToBase64String()
A Base64 string is shorter. It uses all letters of the alphabet, digits and a few punctuation characters, so it's not hexadecimal. Base64 uses 4 characters for 3 bytes, while a hex string uses 6 characters for 3 bytes.
@Eric: there are situations where Base64 is not a good choice because of the extra punctuation characters that are used (passing it in a URL for example)
|
70

I always found this to be the most convenient:

string hashPassword = BitConverter.ToString(byteHashedPassword).Replace("-","");

For some odd reason BitConverter likes to put dashes between bytes, so the replace just removes them.

Update: If you prefer "lowercase" hex, just do a .ToLower() and boom.

Do note that if you are doing this as a tight loop and many ops this could be expensive since there are at least two implicit string casts and resizes going on.

1 Comment

does the same as @PhilippeLeybaert solution, but in one-line.
31

You can use Convert.ToBase64String and Convert.FromBase64String to easily convert byte arrays into strings.

Comments

26

If you're in the 'Hex preference' camp you can do this. This is basically a minimal version of the answer by Philippe Leybaert.

string.Concat(hash.Select(x => x.ToString("X2")))

B1DB2CC0BAEE67EA47CFAEDBF2D747DF

Comments

10

Well as it is a hash, it has possibly values that cannot be shown in a normal string, so the best bet is to convert it to Base64 encoded string.

string s = Convert.ToBase64String(bytes);

and use

byte[] bytes = Convert.FromBase64(s);

to get the bytes back.

Comments

7

Well, you could use the string constructor that takes bytes and an encoding, but you'll likely get a difficult to manage string out of that since it could contain lots of fun characters (null bytes, newlines, control chars, etc)

The best way to do this would be to encode it with base 64 to get a nice string that's easy to work with:

string s = Convert.ToBase64String(bytes);

And to go from that string back to a byte array:

byte[] bytes = Convert.FromBase64String(s);

Comments

6

I know this is an old question, but I thought I would add you can use the built-in methods (I'm using .NET 6.0):

  • Convert.ToBase64String(hashBytes); (Others have already mentioned this)
  • Convert.ToHexString(hashBytes);

1 Comment

and Convert.ToHexStringLower(hashBytes) if you care about lower case
0

For anyone interested a Nuget package I created called CryptoStringify allows you to convert a string to a hashed string using a nice clean syntax, without having to play around with byte arrays:

using (MD5 md5 = MD5.Create())
{
    string strHashedPassword = md5.Hash(password);
}

It's an extension method on HashAlgorithm and KeyedHashAlgorithm so works on SHA1, HMACSHA1, SHA256 etc too.

https://www.nuget.org/packages/cryptostringify

Comments

0

I'm late to the party, but here is a faster version than Philippe Leybaert's answer:

public static class BytesToHexStringHelpers
{       
    public static string ToHexString(this byte[] bytes)
        => ToHexString(bytes, 0, bytes.Length);
        
    public static string ToHexString(this byte[] bytes, int startIndex, int length)
    {
        const string HexadecimalUppercase = "0123456789ABCDEF";
        
        var hexChars = new char[length * 2];
        var hexCharsIndex = 0;
        var endIndex = startIndex + length;
        
        for (var bytesIndex = startIndex; bytesIndex < endIndex; bytesIndex++)
        {
            hexChars[hexCharsIndex++] = HexadecimalUppercase[bytes[bytesIndex] >> 4];
            hexChars[hexCharsIndex++] = HexadecimalUppercase[bytes[bytesIndex] & 0xF];
        }

        return new string(hexChars);
    }
}

In .NET5 and above System.Convert.ToHexString(...) is probably best.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.