title: sha256 encryption in raw javascript
body: <p>I'm trying to encrypt a string to HMAC SHA256 within raw javascript using a <a href="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.js" rel="nofollow noreferrer">web-hosted library</a> but it doesn't seem to work.
  I'm trying to do this to call the <a href="https://developers.coinbase.com/api/v2?javascript#api-key" rel="nofollow noreferrer">Coinbase API</a>. You need to give a few values with the GET request including a Signature, which is where I am experiencing problems. The signature needs to be HMAC SHA256 encrypted. The signature should include the following:</p>
  <blockquote>
  <p>The <code>CB-ACCESS-SIGN</code> header is generated by creating a sha256 HMAC using the secret key on the prehash string <code>timestamp + method + requestPath + body</code> (where + represents string concatenation). The timestamp value is the same as the <code>CB-ACCESS-TIMESTAMP</code> header.</p>
  <p>The <code>body</code> is the request body string or omitted if there is no request body (typically for GET requests).</p>
  <p>The <code>method</code> should be UPPER CASE.</p>
  </blockquote>
  <p>What I think they are saying is that I can leave out the body because it's a GET request.</p>
  <p>My code is the following:</p>
  <p>The HTML library call:</p>
  <pre><code>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.js&quot;&gt;&lt;/script&gt;
  </code></pre>
  <p>The Javascript Encryption and GET request:</p>
  <pre><code>url = &quot;https://api.coinbase.com/v2/accounts&quot;
  var xmlHttp1 = new XMLHttpRequest();
  xmlHttp1.open( &quot;GET&quot;, &quot;https://api.coinbase.com/v2/time&quot;, false);
  xmlHttp1.send( null )
  ts = xmlHttp1.responseText;
  var ts1 = JSON.parse(ts)
  var message = ts1.data.epoch + &quot;GET&quot; + url + &quot;&quot;
  sha256(message);
  var hash = sha256.hmac.create('key');
  
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( &quot;GET&quot;, url, false ); // false for synchronous request
  xmlHttp.setRequestHeader(&quot;CB-ACCESS-KEY&quot;, &quot;XXXXXXXXXXXXXXXX&quot;);
  xmlHttp.setRequestHeader(&quot;CB-ACCESS-TIMESTAMP&quot;, ts1.data.epoch);
  xmlHttp.setRequestHeader(&quot;CB-ACCESS-SIGN&quot;, hash);
  xmlHttp.send( null );
  </code></pre>
  <p>The coinbase API is responding with:</p>
  <pre><code>{&quot;errors&quot;:[{&quot;id&quot;:&quot;authentication_error&quot;,&quot;message&quot;:&quot;invalid signature&quot;}]}
  </code></pre>
  <p>meaning that everything is correct, except for the signature.</p>