Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA256 hash the body and base64 encode in Python Vs TypeScript

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.

like image 281
GThree Avatar asked May 15 '19 15:05

GThree


1 Answers

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.

like image 186
GThree Avatar answered Sep 19 '22 17:09

GThree