代码之家  ›  专栏  ›  技术社区  ›  RanSh

用python转换md5sum

  •  0
  • RanSh  · 技术社区  · 10 年前

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

        # 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)。
    我该怎么做?

    1 回复  |  直到 10 年前
        1
  •  0
  •   Cong Ma    10 年前

    为什么不直接使用 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
    

    我建议你去 摘要() 方法,避免重新发明车轮。


    编辑:

    要使用它从文件中构建校验和,通常需要执行以下操作(在伪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 2 , Python 3 )了解更多信息。