2015-10-07 67 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