python - 如何在 Python3 和 Mac/Linux 终端中获得相同的哈希值?

标签 python python-3.x macos hashlib

如何在终端 (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

最佳答案

内置的 echo 将添加一个尾随换行符,产生不同的字符串,从而产生不同的散列。这样做

echo -n 'test text' | shasum -a 256

如果你确实打算也散列换行符(我建议不要这样做,因为它违反了 POLA ),它需要像这样在 python 中修复

hashlib.sha256("{}\n".format("test text").encode('utf-8')).hexdigest()

关于python - 如何在 Python3 和 Mac/Linux 终端中获得相同的哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49845841/

相关文章:

python - 如何编写在其内部连接中使用复杂的 "on"子句的 Django 查询?

python - 如何对假设策略实现相对约束?

python - 查看 multiprocessing.queue?

python-3.x - 使用 OpenCV 比较两个图像

objective-c - 将distinctUnionOfObjects与NSArrayController和NSTableView一起使用

macos - Unity项目没有解决方案文件

c - 使用 arduino 和 C 初始化串行接口(interface)

python - 实时更新matplotlib Pie

python - 替换未知的先验组数 - 正则表达式 python

python - 如何处理 C 和 Python 之间的 IPC?