2015-10-07 31 views
1

我不想重新創建可能已經存在的模塊。但對programiz解釋如何得到一個很好的例子了SHA-1的消息摘要用一種方法獲取二進制摘要密鑰的Python哈希模塊

# Python rogram to find the SHA-1 message digest of a file 

# import hashlib module 
import hashlib 

def hash_file(filename): 
    """"This function returns the SHA-1 hash 
    of the file passed into it""" 

    # make a hash object 
    h = hashlib.sha1() 

    # open file for reading in binary mode 
    with open(filename,'rb') as file: 

     # loop till the end of the file 
     chunk = 0 
     while chunk != b'': 
      # read only 1024 bytes at a time 
      chunk = file.read(1024) 
      h.update(chunk) 

    # return the hex representation of digest 
    return h.hexdigest() 

message = hash_file("track1.mp3") 
print(message) 

現在我剛剛創建了一個.py我進口,但想知道如果這樣的方法hashlib模塊或另一個已經存在維護良好的模塊?

所以我只能去

import some_hashlib_module 
print some_hashlib_module.get_binary_SH1_digest("File of interest") 
+0

兼容它可能是有意義的傳遞文件類對象的函數,而不是文件名,例如,[爲遠程tarball中的所有文件計算散列值](http://stackoverflow.com/a/27606823/4279)。 – jfs

回答

2

沒有,有沒有現成的函數標準庫的任意位置來計算一個文件對象的摘要。你所展示的代碼是用Python做到這一點的最佳方式。

計算文件散列並不是一個經常出現的專用函數。此外,還有許多不同類型的數據流,您希望以不同的方式處理數據;例如,當從URL下載數據時,您可能希望將計算哈希與將數據同時寫入文件相結合。因此,用於處理散列的當前API與其獲得的一樣通用;設置哈希對象,重複給它提供數據,提取哈希。

您使用可寫了一個小更緊湊,並支持多種的哈希算法的功能:

import hashlib 

def file_hash_hexhdigest(fname, hash='sha1', buffer=4096): 
    hash = hashlib.new(hash) 
    with open(fname, "rb") as f: 
     for chunk in iter(lambda: f.read(buffer), b""): 
      hash.update(chunk) 
    return hash.hexdigest() 

以上是既Python 2和Python 3的

+0

非常感謝您的答案和代碼優化 – Norfeldt