用于查找文件哈希值的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


哈希函数接收任意量的数据并返回一个固定长度的位字符串。该函数的输出称为摘要消息。

它们被广泛用于密码学中的身份验证目的。有许多哈希函数,如 MD5、SHA-1 等。请参考此页面了解更多关于密码学中的哈希函数

在本例中,我们将演示如何对文件进行哈希处理。我们将使用 SHA-1 哈希算法。SHA-1 的摘要长度为 160 位。

我们不会一次性输入文件中的所有数据,因为有些文件非常大,无法一次性装入内存。将文件分成小块将使处理过程更节省内存。

查找哈希值的源代码

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

# importing the hashlib module
import hashlib

def hash_file(filepath):
   """"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(filepath,'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")    # Use path of the file
print(message)

输出

633d7356947eec543c50b76a1852f92427f4dca9

在此程序中,我们以二进制模式打开文件。哈希函数位于 hashlib 模块中。我们使用 while 循环一直循环到文件末尾。当到达末尾时,我们得到一个空的字节对象。

在每次迭代中,我们只从文件中读取 1024 字节(此值可根据我们的意愿更改)并更新哈希函数。

最后,我们使用 hexdigest() 方法以十六进制表示形式返回摘要消息。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战