【问题标题】:MD5 returning different hash codes - PythonMD5 返回不同的哈希码 - Python
【发布时间】:2015-04-13 17:20:24
【问题描述】:

我正在尝试确定某些文件的数据一致性。然而,MD5 不断出现不同的情况。当我执行md5sum 时,哈希值相等:

import hashlib
import os
import sys

def hash_file_content(path):
    try:
        if not os.path.exists(path):
            raise IOError, "File does not exist"
        encode = hashlib.md5(path).hexdigest()
        return encode
    except Exception, e:
        print e

def main():
    hash1 = hash_file_content("./downloads/sample_file_1")
    hash2 = hash_file_content("./samples/sample_file_1")

    print hash1, hash2

if __name__ == "__main__":
   main()

输出出乎意料的不同:

baed6a40f91ee5c44488ecd9a2c6589e 490052e9b1d3994827f4c7859dc127f0

现在md5sum:

md5sum ./samples/sample_file_1
9655c36a5fdf546f142ffc8b1b9b0d93  ./samples/sample_file_1

md5sum ./downloads/sample_file_1 
9655c36a5fdf546f142ffc8b1b9b0d93  ./downloads/sample_file_1

为什么会发生这种情况,我该如何解决?

【问题讨论】:

    标签: python hash md5


    【解决方案1】:

    在您的代码中,您计算​​的是文件路径的md5,而不是文件内容:

    ...
    encode = hashlib.md5(path).hexdigest()
    ...
    

    相反,计算文件内容的 md5:

    with open(path, "r") as f:
        encode = md5(f.read()).hexdigest()
    

    这应该会为您提供匹配的输出(即相互匹配并且与 md5sum 相同)。


    由于文件很大,单次执行f.read() 会太费力,而且当文件大小超过可用内存时根本无法工作。

    因此,相反,利用 md5 在内部使用其更新方法计算块的哈希值,并定义一个使用 md5.update 的方法,并在代码中调用它,如 this answer 中所述:

    import hashlib
    
    def md5_for_file(filename, block_size=2**20):
        md5 = hashlib.md5()
        with open(filename, "rb") as f:
            while True:
                data = f.read(block_size)
                if not data:
                    break
                md5.update(data)
        return md5.digest()
    

    现在在你的代码中调用它:

    encode = md5_for_file(path)
    

    【讨论】:

    • 文件很大,有些是千兆字节... f.read() 是正确使用的,或者只是文件的一个标记,比如说 1024?
    • @philippe f.read() 太费力了。在这种情况下使用此处提到的方法-> stackoverflow.com/a/1131255/1860929,已将其编辑到我的答案中。
    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2011-05-17
    • 2015-02-25
    • 2018-09-05
    相关资源
    最近更新 更多