如何使用Python找到ISO文件的MD5哈希?

3 python iso md5 hashlib

我正在编写一个简单的工具,允许我快速检查下载的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()
Run Code Online (Sandbox Code Playgroud)

当我尝试获取文件的MD5哈希时,我的问题是在第9行.我得到了Type Error:对象,支持所需的缓冲区API.任何人都可以阐明如何使这个功能工作?

小智 8

创建的对象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
Run Code Online (Sandbox Code Playgroud)