How do I find the MD5 hash of an ISO file using Python?
我正在编写一个简单的工具,使我可以快速检查下载的ISO文件的MD5哈希值。 这是我的算法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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的对象。 谁能阐明如何使此功能起作用?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |
您需要阅读文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import sys import hashlib def main(): filename = sys.argv[1] # Takes the ISO 'file' as an argument in the command line testFile = open(filename,"rb") # Opens and reads the ISO 'file' # Use hashlib here to find MD5 hash of the ISO 'file'. This is where I'm having problems m = hashlib.md5() while True: data = testFile.read(4*1024*1024) if not data: break m.update(data) hashedMd5 = m.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() |
您可能需要以二进制(" rb")打开文件,并以块的形式读取数据块。 ISO文件可能太大而无法容纳在内存中。