Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell?

A Python MD5 hash is different than the one created by the md5sum command on the shell. Why?

>>> import hashlib
>>> h = hashlib.md5()
>>> h.update("mystringforhash")
>>> print h.hexdigest()
86b6423cb6d211734fc7d81bbc5e11d3 # Result from Python




$ echo mystringforhash | md5sum
686687dd68c5de717b34569dbfb8d3c3  - # Result on the shell
10949 次浏览

echo附加了一个 \n,因为您通常不希望在 shell 中不以换行符结束的行(如果提示符不从最左边开始,那么它看起来真的很丑陋)。
使用 -n参数省略后面的换行符,它将打印与 python 脚本相同的校验和:

> echo -n mystringforhash | md5sum
86b6423cb6d211734fc7d81bbc5e11d3  -