【问题标题】:Converting md5sum with python用python转换md5sum
【发布时间】:2015-09-03 17:33:26
【问题描述】:

我知道如何找到文件的校验和:

    # Print checksum of the file
    file = os.popen("md5sum -t " + indir + "/" + binfile)
    checksum = file.read().split(' ')[0]
    print "Checksum of " + binfile + " is " + checksum

但是,校验和是一个 32 个字符的字符串。
现在,我想将此校验和转换为 16 个字符的字符串,这样每个字符将代表校验和中的 2 个字符(例如,“63”将是 ascii 字符 0x63)。
我该怎么做?

【问题讨论】:

  • 旁注:不要使用os.popen。它自 Python 2.6 起已被弃用。

标签: python-2.7 md5sum


【解决方案1】:

为什么不直接使用hashlib

当您使用与hashlib 兼容的哈希实现(例如hashlib.md5)时,哈希对象提供了一个方法digest(),可以满足您的要求。

例子:

>>> import hashlib
>>> h = hashlib.md5("something")
>>> h.digest()
'C{\x93\r\xb8K\x80y\xc2\xdd\x80Jq\x93k_'
>>> hextxtdigest = h.hexdigest()
>>> hextxtdigest
'437b930db84b8079c2dd804a71936b5f'
>>> # The next line reinvents the wheel.
>>> whatyouwant = "".join([chr(int(hextxtdigest[x:x + 2], 16)) for x in xrange(0, len(hextxtdigest), 2)])
>>> whatyouwant == h.digest()
True

我建议您使用digest() 方法,避免重新发明轮子。


编辑:

要使用它从文件构建校验和,您通常会执行类似(在伪 Python 中)

import hashlib
h = hashlib.md5()
open some file ...
read some bytes from file
h.update(those bytes read)
repeat read-and-update until end of file ...
close file

在此之后,哈希对象h 将准备好获取您想要的摘要。有关更多信息,请参阅标准库文档(Python 2Python 3)。

【讨论】:

  • 非常感谢,但是您用 "".join()... 的回复对我有用,而 h.digest() 没有用。
  • 也许 digest() 没有工作,因为我没有使用 h.update()。
  • @RanSh 如果您在使用hashlib 时遇到问题,可以尝试打开一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-28
  • 1970-01-01
  • 2017-02-24
相关资源
最近更新 更多