我正在尝试确定某些文件的数据一致性。然而,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
为什么会发生这种情况,我该如何解决?
最佳答案
在您的代码中,您正在计算文件路径的 md5
,而不是文件内容:
...
encode = hashlib.md5(path).hexdigest()
...
相反,计算文件内容的 md5:
with open(path, "r") as f:
encode = md5(f.read()).hexdigest()
这应该会为您提供匹配的输出(即相互匹配并且与 md5sum
相同)。
由于文件很大,单次执行 f.read()
会很费力,而且当文件大小超过您的可用内存时根本无法工作。
因此,取而代之的是,在内部,md5 使用其更新方法来计算 block 上的散列,并定义一个使用 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)
关于python - MD5 返回不同的哈希码 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28486513/