gpt4 book ai didi

python - 如何使用 Python 查找 ISO 文件的 MD5 哈希值?

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:48 24 4
gpt4 key购买 nike

我正在编写一个简单的工具,可以让我快速检查下载的 ISO 文件的 MD5 哈希值。这是我的算法:

import sys
import hashlib

def main():
filename = sys.argv[1] # Takes the ISO 'file' as an argument in the command line
testFile = open(filename, "r") # Opens and reads the ISO 'file'

# Use hashlib here to find MD5 hash of the ISO 'file'. This is where I'm having problems
hashedMd5 = hashlib.md5(testFile).hexdigest()

realMd5 = input("Enter the valid MD5 hash: ") # Promt the user for the valid MD5 hash

if (realMd5 == hashedMd5): # Check if valid
print("GOOD!")
else:
print("BAD!!")

main()

当我尝试获取文件的 MD5 哈希时,我的问题出现在第 9 行。我收到类型错误:支持所需缓冲区 API 的对象。谁能阐明如何使此功能发挥作用?

最佳答案

hashlib.md5 创建的对象不带文件对象。您需要一次向它提供一段数据,然后请求哈希摘要。

import hashlib

testFile = open(filename, "rb")
hash = hashlib.md5()

while True:
piece = testFile.read(1024)

if piece:
hash.update(piece)
else: # we're at end of file
hex_hash = hash.hexdigest()
break

print hex_hash # will produce what you're looking for

关于python - 如何使用 Python 查找 ISO 文件的 MD5 哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6727926/

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