3

ダウンロードした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をサポートするオブジェクト。誰かがこの機能を機能させる方法に光を当てることができますか?

4

2 に答える 2

8

によって作成されたオブジェクトhashlib.md5は、ファイルオブジェクトを取りません。一度に1つずつデータをフィードしてから、ハッシュダイジェストをリクエストする必要があります。

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
于 2011-07-18T01:30:15.527 に答える
3

ファイルを読む必要があります:

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ファイルは大きすぎてメモリに収まらない可能性があります。

于 2011-07-18T01:29:48.907 に答える