6
votes

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

1
I thought it might works with b'test test' instead of encoding it as utf-8, but it doesn't seem to...Ben
Question (that was deleted) asking for possible duplicate of: stackoverflow.com/questions/5693360/… It is the same root cause, but different commands on the terminal and in Python. The old answer is Python2, in Python3 you need to explicit encode with str("test text").encode('utf-8'). So I will almost say no.Punnerud
You don't need the str constructor call, so better leave that out. Also here the OP is shasum, so there is a slight benefit in googleability for keeping this (but closed as dup)vidstige

1 Answers

9
votes

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()