SHA256 hash the body and base64 encode in Python Vs TypeScript

為{幸葍}努か 提交于 2019-12-11 02:04:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/56153113/sha256-hash-the-body-and-base64-encode-in-python-vs-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!