3

I want to HMAC SHA256 hash the normalized request using the client secret and base64 encode the result. I am getting different result in python and typeScript. My goal is to achieve python result in typeScript. How to do that?

I was able to convert hashlib.sha256 (Here is my approach) to typeScript equivalent but not sure about hmac.new

Python 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)

Output:

b'm4nZSWE3Y/tPXToy/0cJMGpR2qpsXgCnF3tsSiZtYt0='

Sample Code

TypeScript 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);

Output:

f1f157335b0982cbba94290163d61582a87352817788b793238817dd631c26d4

Sample Code

1 Answer 1

1

I found the answer. This is very silly mistake where I spent 1 day. Hope this would save someone's day.

Code:

var crypto = require('crypto');

// Below was silly mistake. In my question those parameters are swapped.
var body = "Hello World"; 
var secret = "MySecret";

var hmac = crypto.createHmac("sha256", secret )
                 .update(body)
                 .digest('base64')
console.log(hmac);

Output:

m4nZSWE3Y/tPXToy/0cJMGpR2qpsXgCnF3tsSiZtYt0=

Sample Code

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.