简体   繁体   English

SHA256使用Python和TypeScript对主体和base64进行哈希处理

[英]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 . 我的目标是在SHA256对主体进行哈希处理,然后使用base64进行编码。 I am converting python code to TypeScript . 我正在将python代码转换为TypeScript

Based on google search, what I understood that, crypto can be used against hashlib and base64 . 根据谷歌搜索,据我了解, crypto可以用于hashlibbase64 Here challenge is, when I use .createHmac then it requires the secret when in python I can directly work with body. 这里的挑战是,当我使用.createHmac时,它需要secret ,而在python中我可以直接使用body。 Is it another way to achieve python result in typeScript ? 是在typeScript获得python结果的另一种方法吗?

NOTE: This is the first time I am seeing python code so please correct me if I am missing something here. 注意:这是我第一次看到python代码,因此,如果我在此处缺少某些内容,请更正我。

Python Code: Python代码:

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 TypeScript代码:使用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 . 我可以使用createHash实现此createHash

TypeScript Code: TypeScript代码:

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 . 可以在这里验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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