Izzy Izzy - 1 year ago 86
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:


I'm expecting the hash to look like this:


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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download