【问题标题】:How to get the same hash in Python3 and Mac / Linux terminal?如何在 Python3 和 Mac / Linux 终端中获得相同的哈希值?
【发布时间】: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


【解决方案1】:

echo 内置将添加一个尾随换行符,产生不同的字符串,从而产生不同的哈希值。就这样吧

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

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

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

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 2015-01-04
    • 2017-10-24
    • 2019-09-20
    • 2020-02-06
    • 2012-01-17
    • 2011-11-12
    • 1970-01-01
    • 2020-09-03
    相关资源
    最近更新 更多