【问题标题】:SHA1 hash differ between openssl and hashlib/pycryptoopenssl 和 hashlib/pycrypto 之间的 SHA1 哈希值不同
【发布时间】:2012-01-17 16:59:58
【问题描述】:

为什么使用 openssl 得到的哈希值与我在 python 中得到的不同?

$ echo "Lorem ipsum" | openssl dgst -sha1 -hex
(stdin)= d0c05753484098c61e86f402a2875e68992b5ca3
$ python
>>> from hashlib import sha1
>>> sha("Lorem ipsum").hexdigest()
'94912be8b3fb47d4161ea50e5948c6296af6ca05'
>>> from Crypto.Hash import SHA
>>> SHA.new("Lorem ipsum").hexdigest()
'94912be8b3fb47d4161ea50e5948c6296af6ca05'

字符串不相等吗?我错过了什么明显的东西吗?

编辑:感谢您发现它。正在从一个文件中传输保存的消息,该文件也遇到同样烦人的换行问题。

$ cat message | openssl dgst -sha1 -hex
'keep whacking your head mate, it wont be the same'
$ echo -n $(cat message) | openssl dgst -sha1 -hex
'ok, you got me, for now' 

【问题讨论】:

  • 常见的,是的,明显的,不是真的。

标签: python openssl pycrypto hashlib


【解决方案1】:

您缺少echo 默认附加的结束行:

echo "Lorem ipsum" | openssl dgst -sha1 -hex
(stdin)= d0c05753484098c61e86f402a2875e68992b5ca3

使用-n 参数,它将回显您给它的字符串,以获得预期的结果:

echo -n "Lorem ipsum" | openssl dgst -sha1 -hex
(stdin)= 94912be8b3fb47d4161ea50e5948c6296af6ca05

【讨论】:

    【解决方案2】:

    echo 在字符串末尾添加换行符

    >>> sha("Lorem ipsum\n").hexdigest()
    'd0c05753484098c61e86f402a2875e68992b5ca3'
    

    【讨论】:

      【解决方案3】:

      echo 在字符串中添加一个换行符。选项 -n 抑制尾随换行:

      > echo -n "Lorem ipsum" | openssl dgst -sha1 -hex
      94912be8b3fb47d4161ea50e5948c6296af6ca05
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-14
        • 1970-01-01
        • 2012-05-20
        • 2023-02-19
        相关资源
        最近更新 更多