2012-01-17 72 views
7

为什么使用openssl的哈希与我在python中获得的哈希不同?openssl和hashlib/pycrypto之间的SHA1哈希差异

$ 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' 
+0

常见的,是的,显而易见的,不是真的。 – Piskvor 2012-01-17 17:04:12

回答

24

你错过的底线是echo将默认追加结束:

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

随着-n参数,它会回显只有您给它的字符串,对于预期的结果:

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

回声是把一个换行符在字符串

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

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

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