title: HMAC SHA256 hash computation in C#
body: <p>I need to calculate the HMAC by using the SHA256 hash function. I have a secret key encoded in base64 format. Also there is an online tool that correctly calculate the HMAC (verified). 
  <a href="http://www.freeformatter.com/hmac-generator.html" rel="noreferrer">http://www.freeformatter.com/hmac-generator.html</a>
  I wrote the following code snippet:</p>
  
  <pre><code>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 =&gt; b.ToString("X2"))).ToLower();
  
      System.Diagnostics.Debug.Assert(signatureHashHex == signatureHashHexExpected);
  }
  </code></pre>
  
  <p>PROBLEM:
  My code does not generate the correct HMAC. I verified different steps by using different online tools and alternative C# implementations. Only the conversion from base64 is not confirmed. What am i missing?</p>
  
  <p>UPDATE:
  Calculated signatureHashHex by my code is "a40e0477a02de1d134a5c55e4befa55d6fca8e29e0aa0a0d8acf7a4370208efc"</p>
  
  <p>ANSWER:
  The issue was caused by a misleading documentation stating the key is provided in Base64 format. See the accepted answer:</p>
  
  <pre><code>var shaKeyBytes = System.Text.Encoding.UTF8.GetBytes(key);
  </code></pre>