SHA512 return in hexadecimal

4

I found an example of encrypting a string with SHA512.

public static string HashedString(string text)
{
    SHA512Managed sha512 = new SHA512Managed();
    byte[] hash = sha512.ComputeHash(Encoding.UTF8.GetBytes(text));
    StringBuilder result = new StringBuilder();

    foreach (byte b in hash)
        result.Append(b);

    return result.ToString();
}

But when I print on the screen the return of this method I realize that the result is in binary and I want it in hex.

    
asked by anonymous 06.09.2018 / 21:44

2 answers

4

That?

public static string HashedString(string text) {
    var sha512 = new SHA512Managed();
    byte[] hash = sha512.ComputeHash(Encoding.UTF8.GetBytes(text));
    var result = new StringBuilder();
    foreach (byte b in hash) result.Append($"{b:x2}");
    return result.ToString();
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

You need to say that you want it in hex if that's what you want. See What does the "$" symbol mean before a string? .

    
06.09.2018 / 22:10
-1

Where is

StringBuilder result = new StringBuilder();

foreach (byte b in hash)
    result.Append(b);

return result.ToString();

replace with

return BitConverter.ToString(hash).Replace("-", "");

That way, you will not have n + 1 strings in the heap, but only 2.

    
06.09.2018 / 22:46