title: What is hmac.new equivalent in node.js?
body: <p>I want to <code>HMAC SHA256</code> hash the normalized request using the client secret and base64 encode the result. I am getting different result in <code>python</code> and <code>typeScript</code>. My goal is to achieve <code>python</code> result in <code>typeScript</code>. How to do that?</p>
  
  <p>I was able to convert <code>hashlib.sha256</code> (<a href="https://stackoverflow.com/questions/56153113/sha256-hash-the-body-and-base64-encode-in-python-vs-typescript">Here is my approach</a>) to <code>typeScript</code> equivalent but not sure about <code>hmac.new</code></p>
  
  <p><strong>Python Code:</strong></p>
  
  <pre><code>import hashlib
  import hmac
  import base64
  
  request = "Hello World";
  secret = "MySecret"
  
  requestBytes = bytes(request.encode('utf-8'))
  secretBytes = bytes(secret.encode('utf-8'))
  hmacConversion = hmac.new(secretBytes, requestBytes, digestmod=hashlib.sha256).digest()
  signature = base64.b64encode(hmacConversion)
  print(signature)
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>b'm4nZSWE3Y/tPXToy/0cJMGpR2qpsXgCnF3tsSiZtYt0='
  </code></pre>
  
  <p><a href="https://repl.it/repls/FirstBruisedQuote" rel="nofollow noreferrer">Sample Code</a></p>
  
  <p><strong>TypeScript Code:</strong></p>
  
  <pre><code>var secret = "Hello World";
  var body = "MySecret";
  
  var hmac = crypto.createHmac("sha256", secret)
                   .update(Buffer.from(body, 'utf-8'))
                   .digest('hex');
  console.log(hmac);
  
  
  var hmac2 = crypto.createHmac("sha256", secret)
                   .update(body, 'utf-8')
                   .digest('hex');
  console.log(hmac2);
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>f1f157335b0982cbba94290163d61582a87352817788b793238817dd631c26d4
  </code></pre>
  
  <p><a href="https://repl.it/repls/ImpishSubtleMicrobsd" rel="nofollow noreferrer">Sample Code</a></p>