简体   繁体   中英

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 that, 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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM