Izzy Izzy - 29 days ago 13
C# Question

Why is this HMAC SHA256 hash I'm creating using the wrong character encoding?

I'm doing this in C# to create a hash:

using (var hmacsha256 = new HMACSHA256(Encoding.ASCII.GetBytes(secret)))
{
return System.Text.Encoding.UTF8.GetString(hmacsha256.ComputeHash(Encoding.ASCII.GetBytes(message)));
}


I use the following JSON:

{
"client_id": "26075235",
"client_version": "1.0.0",
"event": "app.uninstall",
"timestamp": "1478741247",
"data": {
"user_id": "62581379",
"site_id": "837771289247593785",
"domain": ""
}
}


and I get this:

sX�m�.-�n�0�v@�i!S��IEC,�56

I'm expecting the hash to look like this:

960aff6c335a87e6077f41066358980a88db54062505875e5a8c363ded9d027e

If I do the hashing like this:

using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
{
return System.Text.Encoding.UTF8.GetString(hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(message)));
}


I get the same thing. How do I return what I'm expecting?

What am I not understanding about this?

L.B L.B
Answer

An arbitrary binary data can not be converted to string... Seems like you want BitConverter.ToString , Convert.ToBase64String or System.Runtime.Remoting.Metadata.W3cXsd2001.SoapBase64Binary, instead of System.Text.Encoding.UTF8.GetString