MD5返回不同的哈希码 - Python

cyb*_*ron 4 python hash md5

我正在尝试确定某些文件的数据一致性.但是,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()
Run Code Online (Sandbox Code Playgroud)

输出意外地不同:

baed6a40f91ee5c44488ecd9a2c6589e 490052e9b1d3994827f4c7859dc127f0
Run Code Online (Sandbox Code Playgroud)

现在md5sum:

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

md5sum ./downloads/sample_file_1 
9655c36a5fdf546f142ffc8b1b9b0d93  ./downloads/sample_file_1
Run Code Online (Sandbox Code Playgroud)

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

mu *_*u 無 6

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

...
encode = hashlib.md5(path).hexdigest()
...
Run Code Online (Sandbox Code Playgroud)

而是,加密文件内容的md5:

with open(path, "r") as f:
    encode = md5(f.read()).hexdigest()
Run Code Online (Sandbox Code Playgroud)

这应该给你匹配的输出(即彼此之间的匹配,并且与之相同md5sum).


由于文件大小很大,f.read()单手操作会太费力,而且当文件大小超过可用内存时,根本不起作用.

因此,利用内部的事实,md5使用其更新方法来计算块上的散列,并定义一个使用该方法的方法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()
Run Code Online (Sandbox Code Playgroud)

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

encode = md5_for_file(path)
Run Code Online (Sandbox Code Playgroud)