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?
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.