Izzy
Izzy

Reputation: 192

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 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?

Upvotes: 0

Views: 2470

Answers (2)

Izzy
Izzy

Reputation: 192

Solved now. I use this string extension method, so to get a lowercase HMAC SHA 256 Hash for a string, I can just do:

mymessage.HmacSha256Digest(mysecret)

public static string HmacSha256Digest(this string message, string secret)
{
    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] keyBytes = encoding.GetBytes(secret);
    byte[] messageBytes = encoding.GetBytes(message);
    System.Security.Cryptography.HMACSHA256 cryptographer = new System.Security.Cryptography.HMACSHA256(keyBytes);

    byte[] bytes = cryptographer.ComputeHash(messageBytes);

    return BitConverter.ToString(bytes).Replace("-", "").ToLower();
}

Upvotes: 2

L.B
L.B

Reputation: 116178

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

Upvotes: 4

Related Questions