Как найти хэш MD5 файла ISO с помощью Python?

Я пишу простой инструмент, который позволяет мне быстро проверять хеш-значения MD5 загруженных файлов ISO. Вот мой алгоритм:

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()

Моя проблема находится в 9-й строке, когда я пытаюсь взять хеш-код файла MD5. Я получаю ошибку типа: объект, поддерживающий требуемый API буфера. Может ли кто-нибудь пролить свет на то, как заставить эту функцию работать?


person Community    schedule 18.07.2011    source источник
comment
Здесь обсуждаются различные подходы: stackoverflow.com/questions/1131220/   -  person zeekay    schedule 18.07.2011
comment
Спасибо! Я видел этот пост и прочитал его, но все еще не полностью понял   -  person    schedule 18.07.2011


Ответы (2)


Объект, созданный 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
person Jeremy    schedule 18.07.2011
comment
Крис, если @ Джереми Бэнкс ответ правильный, отметьте это так. - person james.garriss; 09.11.2011

Вам необходимо прочитать файл:

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, вероятно, слишком велик для размещения в памяти.

person hughdbrown    schedule 18.07.2011