2011-07-18 20 views
3

ダウンロードしたISOファイルのMD5ハッシュ値をすばやく確認できる簡単なツールを書いています。私のアルゴリズムは次の通りです:Pythonを使用して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をサポートするオブジェクトが必要です。誰でもこの機能を動作させる方法を明らかにしてもらえますか?

+0

様々なアプローチ:http://stackoverflow.com/questions/1131220/get-md5-hash-of-a-files-without-open-it-in-python – zeekay

+0

ありがとう!私はその投稿を見て、それを読むが、まだ完全に理解していない –

答えて

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

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 
+1

美しい、ありがとう! –

+1

Chrisさん、@Jeremy Banksの回答が正しい場合は、マークを付けてください。 –

関連する問題