Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA1 hash differ between openssl and hashlib/pycrypto

Why does the hash from using openssl differ from the ones I get in 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'

Are the strings not equivalent? am I missing something obvious?

Edit: Thanks for spotting it. Was piping a saved message from a file which also suffer from the same annoying newline issue.

$ 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' 
like image 498
ib.lundgren Avatar asked Jan 17 '12 16:01

ib.lundgren


3 Answers

You're missing the endline that echo will append by default:

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

With the -n parameter, it will echo only the string that you gave it, for expected result:

echo -n "Lorem ipsum" | openssl dgst -sha1 -hex
(stdin)= 94912be8b3fb47d4161ea50e5948c6296af6ca05
like image 185
Piskvor left the building Avatar answered Oct 15 '22 21:10

Piskvor left the building


echo is putting a newline at the end of the string

>>> sha("Lorem ipsum\n").hexdigest()
'd0c05753484098c61e86f402a2875e68992b5ca3'
like image 41
John La Rooy Avatar answered Oct 15 '22 20:10

John La Rooy


echo adds a newline character to the string. The option -n suppresses the tailing newline:

> echo -n "Lorem ipsum" | openssl dgst -sha1 -hex
94912be8b3fb47d4161ea50e5948c6296af6ca05
like image 1
dmeister Avatar answered Oct 15 '22 21:10

dmeister