"The specified value has invalid control characters" when converting SHA512 output to string

I am trying to create a Hash for the API. my input looks something like this:

FBN | Web | 3QTC0001 | RS1 | 260214133217 | 000000131127897656

And my expected result is as follows:

17361DU87HT56F0O9967E34FDFFDFG7UO334665324308667FDGJKD66F9888766DFKKJJR466634HH6566734JHJH34766734NMBBN463499876554234343432456

I tried, but I keep getting "The specified value has invalid control characters. Parameter name: value"

I really do this in a REST service.

public static string GetHash(string text)
{
    string hash = "";
    SHA512 alg = SHA512.Create();
    byte[] result = alg.ComputeHash(Encoding.UTF8.GetBytes(text));
    hash = Encoding.UTF8.GetString(result);        
    return hash;
}

What am I missing?

+3
source share
3 answers

Encoding.UTF8.GetString(result), result UTF-8 ( goo!), - , - .

byte[] ; UTF-8.

. ? hex string ?, .

+3

, byte

var builder = new StringBuilder();
foreach(var b in result) {
  builder.AppendFormat("{0:X2}", b);
}
return builder.ToString();
+2

You might want to use Base64 encoding (AKA UUEncode):

public static string GetHash(string text)
{
    SHA512 alg = SHA512.Create();
    byte[] result = alg.ComputeHash(Encoding.UTF8.GetBytes(text));
    return Convert.ToBase64String(result);
}

For your example string, the result

OJgzW5JdC1IMdVfC0dH98J8tIIlbUgkNtZLmOZsjg9H0wRmwd02tT0Bh/uTOw/Zs+sgaImQD3hh0MlzVbqWXZg==

It has the advantage of being more compact than encoding each byte into two characters: three bytes take four characters with Base64 encoding or six characters in another way.

+1
source

All Articles