作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如何在终端 (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/
我是一名优秀的程序员,十分优秀!