为什么 Python 创建的 MD5 哈希与在 shell 中使用 echo 和 md5sum 创建的不同? [英] Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell?

查看:34
本文介绍了为什么 Python 创建的 MD5 哈希与在 shell 中使用 echo 和 md5sum 创建的不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python MD5 哈希不同于在 shell 上由 md5sum 命令创建的哈希.为什么?

<预><代码>>>>导入哈希库>>>h = hashlib.md5()>>>h.update("mystringforhash")>>>打印 h.hexdigest()86b6423cb6d211734fc7d81bbc5e11d3 # Python 的结果$ echo mystringforhash |md5sum686687dd68c5de717b34569dbfb8d3c3 - # shell 上的结果

解决方案

echo 附加一个 因为您通常不希望行中不以换行符结尾shell(如果提示不是从最左边开始,它看起来真的很难看).
使用 -n 参数省略尾随换行符,它将打印与您的 python 脚本相同的校验和:

>echo -n mystringforhash |md5sum86b6423cb6d211734fc7d81bbc5e11d3 -

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

解决方案

echo appends a 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  -

这篇关于为什么 Python 创建的 MD5 哈希与在 shell 中使用 echo 和 md5sum 创建的不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆