title: HmacSHA1 different result in Node crypto and CryptoJS
body: <p>I am implementing two factor authentication with Google Authenticator in a NativeScript app starting from <a href="https://hackernoon.com/how-to-implement-google-authenticator-two-factor-auth-in-javascript-091wy3vh3" rel="nofollow noreferrer">this implementation</a>. Since Node's crypto module doesn't run inside NativeScript, I am trying to make it work with CryptoJS.</p>
  
  <p>This is the working Node code. The function returns a buffer with the correct value.</p>
  
  <pre class="lang-js prettyprint-override"><code>const crypto = require('crypto');
  
  function generateHOTP(secret, counter) {
      const buffer = Buffer.alloc(8);
      for (let i = 0; i &lt; 8; i++) {
         buffer[7 - i] = counter &amp; 0xff;
         counter = counter &gt;&gt; 8;
      }
  
      const hmac = crypto.createHmac('sha1', secret);
      hmac.update(buffer);
      return hmac.digest();
  }
  </code></pre>
  
  <p>This is the CryptoJS equivalent. The value returned is different than the previous function, and sometimes it returns the same value for many iterations regardless of the input.</p>
  
  <pre class="lang-js prettyprint-override"><code>const CryptoJS = require("crypto-js");
  
  function generateHOTP(secret, counter) {
      const buffer = Buffer.alloc(8);
      for (let i = 0; i &lt; 8; i++) {
         buffer[7 - i] = counter &amp; 0xff;
         counter = counter &gt;&gt; 8;
      }
  
      let result = CryptoJS.HmacSHA1(buffer.toString(), secret); // buffer.toString() is the problem
      return Buffer.from(result.toString(), "hex");
  }
  </code></pre>
  
  <p>If in the first function I change <code>hmac.update(buffer)</code> to <code>hmac.update(buffer.toString())</code>, it returns the same wrong value as the second one, so the issue lies in this string conversion. <code>buffer</code> is an UInt8Array.</p>
  
  <p>How can I fix the first parameter of <code>CryptoJS.HmacSHA1(message, key)</code> to return the same value as the first function?</p>