7

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' 
ib.lundgren
  • 1,454
  • 14
  • 15

3 Answers3

25

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
Piskvor left the building
  • 87,797
  • 43
  • 170
  • 220
6

echo is putting a newline at the end of the string

>>> sha("Lorem ipsum\n").hexdigest()
'd0c05753484098c61e86f402a2875e68992b5ca3'
John La Rooy
  • 263,347
  • 47
  • 334
  • 476
1

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

> echo -n "Lorem ipsum" | openssl dgst -sha1 -hex
94912be8b3fb47d4161ea50e5948c6296af6ca05
dmeister
  • 32,008
  • 19
  • 67
  • 92