【发布时间】:2018-04-15 19:17:17
【问题描述】:
如何在终端 (Mac/Linux) 和 Python 中获得相同的 sha256 哈希?
尝试了以下示例的不同版本,并在 StackOverflow 上搜索。
终端:
echo 'test text' | shasum -a 256
c2a4f4903509957d138e216a6d2c0d7867235c61088c02ca5cf38f2332407b00
Python3:
import hashlib
hashlib.sha256(str("test text").encode('utf-8')).hexdigest()
'0f46738ebed370c5c52ee0ad96dec8f459fb901c2ca4e285211eddf903bf1598'
更新: 与Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell? 不同,因为在 Python3 中您需要显式编码,而我需要 Python 中的解决方案,而不仅仅是在终端中。 “重复”不适用于文件:
example.txt 内容:
test text
终端:
shasum -a 256 example.txt
c2a4f4903509957d138e216a6d2c0d7867235c61088c02ca5cf38f2332407b00
【问题讨论】:
-
我认为它可能适用于
b'test test'而不是将其编码为 utf-8,但它似乎并不... -
问题(已删除)要求可能重复:stackoverflow.com/questions/5693360/… 这是相同的根本原因,但终端和 Python 中的命令不同。旧答案是 Python2,在 Python3 中,您需要使用 str("test text").encode('utf-8') 进行显式编码。所以我几乎会说不。
-
您不需要
str构造函数调用,所以最好不要使用它。同样这里的 OP 是shasum,因此保留它的 googleability 有一点好处(但作为 dup 关闭)
标签: python python-3.x macos hashlib