gpt4 book ai didi

python - 如何在 Python 中计算文件的 MD5 校验和?

转载 作者:IT老高 更新时间:2023-10-28 20:28:53 25 4
gpt4 key购买 nike

我用 Python 编写了一些代码,用于检查文件中的 MD5 哈希并确保哈希与原始哈希匹配。

这是我开发的:

# Defines filename
filename = "file.exe"

# Gets MD5 from file
def getmd5(filename):
return m.hexdigest()

md5 = dict()

for fname in filename:
md5[fname] = getmd5(fname)

# If statement for alerting the user whether the checksum passed or failed

if md5 == '>md5 will go here<':
print("MD5 Checksum passed. You may now close this window")
input ("press enter")
else:
print("MD5 Checksum failed. Incorrect MD5 in file 'filename'. Please download a new copy")
input("press enter")
exit

但是每当我运行代码时,我都会收到以下错误:

Traceback (most recent call last):
File "C:\Users\Username\md5check.py", line 13, in <module>
md5[fname] = getmd5(fname)
File "C:\Users\Username\md5check.py, line 9, in getmd5
return m.hexdigest()
NameError: global name 'm' is not defined

我的代码中有什么遗漏吗?

最佳答案

关于您的错误以及您的代码中缺少的内容。 m 是一个没有为 getmd5() 函数定义的名称。

无意冒犯,我知道您是初学者,但您的代码到处都是。让我们一一看看你的问题:)

首先,您没有正确使用 hashlib.md5.hexdigest() 方法。请引用 Python Doc Library 中关于 hashlib 函数的解释。 .为提供的 string 返回 MD5 的正确方法是执行以下操作:

>>> import hashlib
>>> hashlib.md5("example string").hexdigest()
'2a53375ff139d9837e93a38a279d63e5'

但是,这里有一个更大的问题。您正在对 文件名字符串 计算 MD5,而实际上 MD5 是根据文件 contents 计算的。您将需要基本上读取文件内容并通过 MD5 管道传输它。我的下一个例子效率不高,但是是这样的:

>>> import hashlib
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'

您可以清楚地看到第二个 MD5 哈希与第一个完全不同。原因是我们正在推送文件的内容,而不仅仅是文件名。

一个简单的解决方案可能是这样的:

# Import hashlib library (md5 method is part of it)
import hashlib

# File to check
file_name = 'filename.exe'

# Correct original md5 goes here
original_md5 = '5d41402abc4b2a76b9719d911017c592'

# Open,close, read file and calculate MD5 on its contents
with open(file_name, 'rb') as file_to_check:
# read contents of the file
data = file_to_check.read()
# pipe contents of the file through
md5_returned = hashlib.md5(data).hexdigest()

# Finally compare original MD5 with freshly calculated
if original_md5 == md5_returned:
print "MD5 verified."
else:
print "MD5 verification failed!."

请看帖子 Python: Generating a MD5 checksum of a file 。它详细解释了如何有效实现它的几种方法。

祝你好运。

关于python - 如何在 Python 中计算文件的 MD5 校验和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16874598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com