10

My goal is to hash the body in SHA256 and then encode it with base64. I am converting python code to TypeScript.

Based on google search, what I understood is, crypto can be used against hashlib and base64. Here challenge is, when I use .createHmac then it requires the secret when in python I can directly work with body. Is it another way to achieve python result in typeScript?

NOTE: This is the first time I am seeing python code so please correct me if I am missing something here.

Python Code:

import hashlib
import base64

body = "johnDoe"
abc =  base64.b64encode(hashlib.sha256(body.encode('utf-8')).digest())
print(abc)

Output:

b'RnuqbBqTNwQ7v3g3tKsVAi+NUALBCUeoRBEq6Yil6RA='

This can be verified here.

TypeScript Code: Using createHmac

var crypto = require('crypto');

var secret = "PYPd1Hv4J6";
var body = "johnDoe";

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

Output:

DLZdA1/ULIIECiJ4t+HYDLE+FRPIfcFQNo7Uw/csopU=

This can be verified here.

1 Answer 1

6

I can achieve this using createHash.

TypeScript Code:

var crypto = require('crypto');

var body = "johnDoe";

var hash = crypto.createHash("sha256");
var hash_result = hash.update(body, 'utf8').digest('base64');
console.log(hash_result);

Output:

RnuqbBqTNwQ7v3g3tKsVAi+NUALBCUeoRBEq6Yil6RA=

This can be verified here.

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.