标签归档:md5sum

为什么Python创建的MD5哈希与在外壳中使用echo和md5sum创建的MD5哈希不同?

问题:为什么Python创建的MD5哈希与在外壳中使用echo和md5sum创建的MD5哈希不同?

Python MD5哈希与shell上md5sum命令创建的哈希不同。为什么?

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


$ echo mystringforhash | md5sum
686687dd68c5de717b34569dbfb8d3c3  - # Result on 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

回答 0

echo追加a,\n因为您通常不希望外壳中的行不以换行符结尾(如果提示不是从最左边开始,则看起来很丑)。
使用-n参数省略尾随的换行符,它将打印与您的python脚本相同的校验和:

> echo -n mystringforhash | md5sum
86b6423cb6d211734fc7d81bbc5e11d3  -

echo appends a \n since you usually do not want lines not ending with a linebreak in your shell (it looks really ugly if the prompt does not start at the very left).
Use the -n argument to omit the trailing linebreak and it will print the same checksum as your python script:

> echo -n mystringforhash | md5sum
86b6423cb6d211734fc7d81bbc5e11d3  -