0

I've been coming against this for a few hours now and I can't seem to find a solution. I'm trying to encrypt a string using SHA512 and put it in a header for HTTP Request. I know that HTTP Headers only like ASCII characters but everytime I generate the encrypted string I only get nonASCII results, is there any way to force ASCII return? Here's my function generating the encryption:

private static string GenerateSignatureHeader(string data, string timestamp){
   //Encode to UTF8 required for SHA512
   byte[] encData = ASCIIEncoding.UTF8.GetBytes (data);
   byte[] hash;         
   using (SHA512 shaM = new SHA512Managed ()) {
       hash = shaM.ComputeHash (encData);
   }
   return ASCIIEncoding.Default.GetString (hash);
}

And adding to HTTP Request here:

request.Headers.Add("signature", GenerateSignatureHeader(body, timestamp));

Is what I'm doing here correct? The error is thrown when trying to add the header to the request:

Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.ArgumentException: invalid header value: 4Ɓj�M�P��hM�$� �s;��6��1!��,�y��.x;��d�G�↌�2�@1'��1� Parameter name: headerValue System.Net.WebHeaderCollection.AddWithoutValidate (string,string) System.Net.WebHeaderCollection.Add (string,string)

So I'm assuming that it's the nonASCII characters that are causing this?

Ross
  • 112
  • 1
  • 17
  • You assumption is correct. see [Illegal characters in HTTP headers](http://stackoverflow.com/questions/19028068/illegal-characters-in-http-headers) – Mehrzad Chehraz May 02 '15 at 11:27

1 Answers1

2

A hash functions return pseudo-random bytes. Such a byte array very likely doesn't correspond to a valid character encoding such as ASCII. That is why you're getting those unprintable character placeholders.

You need to encode the output. For example using Base64 or Hex.

return System.Convert.ToBase64String(hash);
Artjom B.
  • 61,146
  • 24
  • 125
  • 222