title: HMAC calculation in SQL compared to C#
body: <p>I need to do a HMAC calculation in SQL (SQL Server 2012) that gives the same value as my calculation in C#, obviously.
  The C# implementation works. It uses the standard .NET class <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha512(v=vs.110).aspx" rel="nofollow">HMACSHA512</a>.</p>
  
  <p>I would like to avoid using SQL CLR, and instead use <a href="https://gist.github.com/rmalayter/3130462" rel="nofollow">this SQL implementation</a> that I belive should work according to other posts.</p>
  
  <p>I'm having a feeling that the problem is the way I'm casting my varchars to varbinaries for the HMAC input parameters. I'm using it like this:</p>
  
  <pre><code>DECLARE @hash VARBINARY(64) = (
      SELECT dbo.HMAC('SHA2_512',         -- Hash alg.
          CAST('1234' AS VARBINARY),      -- Key
          CAST('12345678' AS VARBINARY))  -- Data
  );
  
  SELECT CONVERT(VARCHAR(max), @hash, 2) hash_varchar
  
  -- Output: 180F85FDA172A3F1CCEAA25D4D63A05C03F0BF8D664A7AD81E2FE1FB2FF3D4BA754B90A75C58B1D2B8A11C52192CAF307658B4B6A81D06ECB2667F37DA753619
  </code></pre>
  
  <p>Calculating the hash for the same key and data using the C# class, yields the following output:</p>
  
  <pre><code>8DB72756190593E0849AC6CA9B0DB4D3E0A1439AB2D9ECD6D07406020EEA6EE824A89C3DA0633B66AFE5BBA8D4CC5AB59347E8137F5AF6521725307B4DC8BCB5
  </code></pre>
  
  <p>For reference, here's my exact C# <a href="https://gist.github.com/thj-dk/47778a7a56a4d98dbd58" rel="nofollow">implementation</a>.</p>
  
  <p>Am I doing something wrong, or is it the implementation of the HMAC function?</p>