title: How to generate HMAC-SHA1 in C#?
body: <p>I am trying to make use of a REST API using C#. The API creator has provided sample libraries in PHP, Ruby and Java. I am getting hung up on one part of it where I need to generate an <a href="http://en.wikipedia.org/wiki/HMAC" rel="noreferrer"><code>HMAC</code></a>.</p>
  
  <p>Here's how it is done in the sample libraries they have provided.</p>
  
  <p><strong>PHP</strong>   </p>
  
  <pre><code>hash_hmac('sha1', $signatureString, $secretKey, false);
  </code></pre>
  
  <p><strong>Ruby</strong>  </p>
  
  <pre><code>digest = OpenSSL::Digest::Digest.new('sha1')
  return OpenSSL::HMAC.hexdigest(digest, secretKey, signatureString)
  </code></pre>
  
  <p><strong>Java</strong></p>
  
  <pre><code>SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA1_ALGORITHM);
  
  Mac mac = null;
  mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
  mac.init(signingKey);
  
  byte[] bytes = mac.doFinal(signatureString.getBytes());
  
  String form = "";
  for (int i = 0; i &lt; bytes.length; i++)
  {
      String str = Integer.toHexString(((int)bytes[i]) &amp; 0xff);
      if (str.length() == 1)
      {
          str = "0" + str;
      }
  
      form = form + str;
  }
  return form;
  </code></pre>
  
  <p><strong>Here's my attempt in C#. <strike>It is not working.</strike> UPDATE:</strong> The C# example below works just fine. I found out that the real problem was due to some cross-platform differences in newline characters in my <code>signatureString</code>.</p>
  
  <pre><code>var enc = Encoding.ASCII;
  HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
  hmac.Initialize();
  
  byte[] buffer = enc.GetBytes(signatureString);
  return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
  </code></pre>