SHA1哈希在openssl和hashlib / pycrypto之间有所不同

时间:2012-01-17 16:59:58

标签: python openssl pycrypto hashlib

为什么使用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' 

3 个答案:

答案 0 :(得分:24)

您错过了echo默认附加的结尾:

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

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

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

答案 1 :(得分:6)

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

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

答案 2 :(得分:1)

echo在字符串中添加换行符。选项-n会抑制拖尾换行符:

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