openssl和hashlib/pycrypto之间的SHA1哈希值不同

7

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

常见的,是的,明显的,其实不太明显。 - Piskvor left the building
3个回答

25

你缺少了echo默认会添加的换行符:

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

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

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

6

echo在字符串的末尾添加一个换行符

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

1

echo 命令会在字符串末尾添加一个换行符。选项 -n 可以抑制这个换行符:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接