MD5返回不同的哈希代码 - Python

4

我正在尝试确定一些文件的数据一致性。然而,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

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

7
在你的代码中,你正在计算文件路径的md5,而不是文件内容的md5
...
encode = hashlib.md5(path).hexdigest()
...

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

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

通过这样做,您应该可以得到匹配的输出(即,彼此匹配,并且与md5sum的结果相同)。


由于文件大小很大,在单个步骤中执行f.read()会过于繁重,并且当文件大小超出可用内存时根本不起作用。

因此,取而代之地,利用md5内部使用其update方法来计算哈希值的事实,并定义一个方法,该方法使用md5.update,并在代码中调用它,如此答案中所述:

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)

文件很大,有些甚至达到了几个GB... f.read() 是正确的使用方式,还是只读取文件的一部分,比如说1024? - cybertextron
@philippe的f.read()操作可能过于繁琐。如果是这种情况,请使用此处提到的方法-> stackoverflow.com/a/1131255/1860929,并已将其编辑到我的答案中。 - Anshul Goyal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接