ARTICLE AD BOX
I'm working on HMAC-SHA256 signature validation in C# and ran into something strange. When I test my code against different online HMAC calculators, I get inconsistent results. My implementation matches one calculator (freeformatter.com), but several other popular calculators all agree on a completely different hash. I'm trying to figure out whether my code has a bug or if those calculators are doing something differently.
My C# Implementation:
private static string CalculateHMACSHA256(string message, string key) { byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] inputBytes = Encoding.UTF8.GetBytes(message); using var hmac = new HMACSHA256(keyBytes); byte[] hashBytes = hmac.ComputeHash(inputBytes); return BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); }Test Case 1: Formatted JSON
Input:
{ "test": "test" }Secret Key: 123
Algorithm: HMAC-SHA256
Output Format: Hexadecimal lowercase
Results
My C# code gives me:
415aa87815342a5b0505fe1c35a9afb0d58ef5ba9c74feaffdcee9c94591a4a7
Matches this calculator:
https://www.freeformatter.com/hmac-generator.htmlBut these calculators all produce a different hash:
46067ae650494e0cb06f9170eabf1eca9b0bf29479142d675508eecedd239668
https://emn178.github.io/online-tools/sha256.html
https://tools.onecompiler.com/hmac-sha256
https://codebeautify.org/hmac-generator
https://www.authgear.com/tools/hmac-signature-generator-verifier
So either my implementation (and freeformatter.com) are both wrong, or those four calculators are handling the input differently somehow.
Context: I'm building an ASP.NET Core API that needs to validate HMAC signatures from a third-party client, and the signatures aren't matching. I need to know if my C# code is actually calculating HMAC-SHA256 correctly.
Test Case 2: Minified JSON
Here's where it gets interesting. When I use minified JSON instead:
Input: {"test":"test"}
Secret Key: 123
This time, all the calculators give me the same result:
158a14842ce68aa9fbf72ebe487f14637f2e18d7d7b4ae8ab383c12904def981
What's going on here? Any insights would be really helpful.
