How to convert a byte array into a string that preserves lowercase?

Viewed 33

im trying to convert a byte array from a hash function into a string, i used a bitconverter.tostring() at first but it just creates a string with all uppercase bytes separated by dashes

This is my basic method

public string Hash(string password)
    {
        using var hasher = SHA512.Create();
        {
            var asBytes = Encoding.Default.GetBytes(password);
            var hashed = hasher.ComputeHash(asBytes);
            string stringhashed = BitConverter.ToString(hashed);
            return stringhashed;
        }
    }

the output hashes correctly, however it gets formated into a string as BYTE-BYTE-BYTE-BYTE-BYTE.... while i needed the output to be a normal string, with lowercase and all. Is there any way to convert a byte array into a string meeting these requirements?

1 Answers

Either use String.Replace() and String.ToLower() to modify the string output from BitConverter.ToString():

return stringhashed.Replace("-", "").ToLower();

... or implement your own stringification extension method:

public static class BitUtils {
    public static string ToHexString(this byte[] bytes)
    {
        StringBuilder sb = new StringBuilder(bytes.Length * 2);
        foreach(byte b in bytes)
        {
            // use the `x` format string to get lowercase hexadecimal
            sb.AppendFormat("{0:x2}", b);
        }

        return sb.ToString();
    }
}

So you can do:

return asBytes.ToHexString();
Related