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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With