SHA256使用Python和TypeScript对主体和base64进行哈希处理 [英] SHA256 hash the body and base64 encode in Python Vs TypeScript

查看:319
本文介绍了SHA256使用Python和TypeScript对主体和base64进行哈希处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是将主体散列到SHA256中,然后使用base64对其进行编码.我正在将python代码转换为TypeScript.

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

基于Google搜索,据我了解,crypto可用于hashlibbase64.这里的挑战是,当我使用.createHmac时,它需要secret,而在python中我可以直接使用body.是在typeScript中获得python结果的另一种方法吗?

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?

注意:这是我第一次看到python代码,因此,如果我在这里遗漏了一些东西,请纠正我.

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

Python代码:

import hashlib
import base64

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

输出:

b'RnuqbBqTNwQ7v3g3tKsVAi+NUALBCUeoRBEq6Yil6RA='

可以在此处进行验证.

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);

输出:

DLZdA1/ULIIECiJ4t+HYDLE+FRPIfcFQNo7Uw/csopU=

可以在此处进行验证.

推荐答案

我可以使用createHash来实现.

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);

输出:

RnuqbBqTNwQ7v3g3tKsVAi+NUALBCUeoRBEq6Yil6RA=

可以在此处进行验证.

这篇关于SHA256使用Python和TypeScript对主体和base64进行哈希处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆