Question

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' 
Was it helpful?

Solution

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

OTHER TIPS

echo is putting a newline at the end of the string

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

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

> echo -n "Lorem ipsum" | openssl dgst -sha1 -hex
94912be8b3fb47d4161ea50e5948c6296af6ca05
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top