Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discrepancy between sha256sum executable and PyCrypto library

I am trying to take the SHA256 sum of an ASCII encoded string. To begin, I tried the sha256sum executable:

$ echo foo | sha256sum
b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c

But when I use the PyCrypto library, I get something different:

from Crypto.Hash import SHA256
h = SHA256.new();
h.update('foo');
print(h.hexdigest());

I get the following:

c5aac592460a9ac7845e341090f6f9c81f201b63e5338ee8948a6fe6830c55dc

I suspect I am missing something about the first one, that is, echo foo might have a delimiter or something, but I haven't been able to figure out what.

What is different about these two situations?

like image 262
tlehman Avatar asked Dec 21 '25 05:12

tlehman


1 Answers

The command echo foo adds a newline at the end of the output, you should use the -n option:

$ echo -n foo | sha256sum
2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae  -
$ python
Python 2.7.3 (default, Sep 26 2012, 21:53:58) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> hashlib.sha256('foo').hexdigest()
'2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
like image 76
Bakuriu Avatar answered Dec 22 '25 18:12

Bakuriu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!