openssl sha256 和 base64 编码的 Python 等效项

问题描述 投票:0回答:1

我有包含此命令的 bash shell 脚本

openssl dgst -binary -sha256 < $body | openssl enc -e -base64 
body 是一个 json 对象。

我需要Python3中的等效命令,你能帮忙吗

这是我尝试过的,编码的字符串与 bash 脚本的输出不匹配 ` 导入 hashlib、base64

hash_object = hashlib.sha256(body.encode('utf-8'))
hex_dig = hash_object.hexdigest()

BYTE_ARRAY = bytearray.fromhex(hex_dig)

打印(f“{BYTE_ARRAY}”) BASE64_VAL = base64.b64encode(BYTE_ARRAY) 打印(f“{BASE64_VAL}”)`

python-3.x openssl
1个回答
0
投票

如果输入正确,对我有用,但您不需要转换为十六进制并返回:

echo test >inputfile; openssl dgst -sha256 -binary <inputfile | openssl base64
-->
8sobtsfpB9Btr+Roflefznazfk6Tt2BQItpS5szCb9I=
import hashlib,base64;
d=open('inputfile','rb').read();
h=hashlib.sha256(d).digest();
print(base64.b64encode(h).decode('ascii'))
-->
8sobtsfpB9Btr+Roflefznazfk6Tt2BQItpS5szCb9I=
© www.soinside.com 2019 - 2024. All rights reserved.