I need to calculate HMAC using the SHA256 hash function. I have a secret key encoded in base64 format. There is also an online tool that correctly calculates HMAC (verified).
http://www.freeformatter.com/hmac-generator.html
I wrote the following code snippet:
var signatureHashHexExpected = "559bd871bfd21ab76ad44513ed5d65774f9954d3232ab68dab1806163f806447";
var signature = "123456:some-string:2016-04-12T12:44:16Z";
var key = "AgQGCAoMDhASFAIEBggKDA4QEhQCBAYICgwOEBIUAgQ=";
var shaKeyBytes = Convert.FromBase64String(key);
using (var shaAlgorithm = new System.Security.Cryptography.HMACSHA256(shaKeyBytes))
{
var signatureBytes = System.Text.Encoding.UTF8.GetBytes(signature);
var signatureHashBytes = shaAlgorithm.ComputeHash(signatureBytes);
var signatureHashHex = string.Concat(Array.ConvertAll(signatureHashBytes, b => b.ToString("X2"))).ToLower();
System.Diagnostics.Debug.Assert(signatureHashHex == signatureHashHexExpected);
}
PROBLEM: My code does not generate the correct HMAC. I checked the various steps using various online tools and alternative C # implementations. Only the conversion from base64 is not confirmed. What am I missing?
UPDATE: The calculated HashHex signature in my code is "a40e0477a02de1d134a5c55e4befa55d6fca8e29e0aa0a0d8acf7a4370208efc"
ANSWER: The problem was caused by misleading documentation that the key is provided in Base64 format. See Accepted Answer:
var shaKeyBytes = System.Text.Encoding.UTF8.GetBytes(key);