Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the same hash in Python3 and Mac / Linux terminal?

How can I get the same sha256 hash in terminal (Mac/Linux) and Python?

Tried different versions of the examples below, and search on StackOverflow.

Terminal:

echo 'test text' | shasum -a 256

c2a4f4903509957d138e216a6d2c0d7867235c61088c02ca5cf38f2332407b00

Python3:

import hashlib
hashlib.sha256(str("test text").encode('utf-8')).hexdigest()

'0f46738ebed370c5c52ee0ad96dec8f459fb901c2ca4e285211eddf903bf1598'

Update: Different from Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell? because in Python3 you need to explicitly encode, and I need the solution in Python, not just in terminal. The "duplicate" will not work on files:

example.txt content:

test text

Terminal:

shasum -a 256 example.txt

c2a4f4903509957d138e216a6d2c0d7867235c61088c02ca5cf38f2332407b00

like image 433
Punnerud Avatar asked Apr 15 '18 19:04

Punnerud


1 Answers

The echo built-in will add a trailing newline yielding a different string, and thus a different hash. Do it like so

echo -n 'test text' | shasum -a 256

If you indeed intended to also hash the newline (I advice against this as it violates POLA), it needs to be fixed up in python like so

hashlib.sha256("{}\n".format("test text").encode('utf-8')).hexdigest()
like image 121
vidstige Avatar answered Sep 21 '22 13:09

vidstige