问题:为什么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  -

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。