[Python] 使用 hashlib 計算檔案的 sha1/md5

[Python] 使用 hashlib 計算檔案的 sha1/md5

Python 很好用的一點就是內建了強大的函式庫,

因此像計算 sha1/md5 之類的事也可以很容易的解決~

要計算 sha1 的話,只要利用 hashlib.sha1() 產生物件,

再呼叫 update() 計算,最後就可以由 hexdigest() 取得結果了~
 

下面是一個範例程式:

 

import hashlib
import os

def _calculate_hash(file_path, method):        
    hash_result =
   
    if (os.path.isfile(file_path)):
        f = open(file_path)
        try:
            # Calculate sha1
            hash_obj = getattr(hashlib, method)()
            hash_obj.update(f.read())
        except:
            pass
        else:
            hash_result = hash_obj.hexdigest().upper()
        finally:
            # Close file
            f.close
   
    # Return “” when hash cannot be calculated
    return hash_result

def calculate_sha1(file_path):
    return _calculate_hash(file_path, “sha1”)

def calculate_md5(file_path):
    return _calculate_hash(file_path, “md5”)

path = “/var/log/messages”
print “sha1”, calculate_sha1(path)
print “md5”, calculate_md5(path)

 

程式執行後的結果會類似下面:

sha1 1E36E6E434FE9136F194D3EA27445E826B46231F
md5 7E9011C8163F0CD793E05E3398802118

 

 

//
//

(本頁面已被瀏覽過 727 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料