原文: https://www.programiz.com/python-programming/examples/hash-file
在本文中,您将学习查找文件的哈希并显示它。
要理解此示例,您应该了解以下 Python 编程主题:
散列函数获取任意数量的数据,并返回固定长度的位字符串。 函数的输出称为摘要消息。
它们被广泛用于密码学中以进行认证。 有许多哈希函数,例如 MD5,SHA-1 等。请参阅此页面,以了解有关密码学中的哈希函数的更多信息。
在此示例中,我们将说明如何对文件进行哈希处理。 我们将使用 SHA-1 哈希算法。 SHA-1 的摘要的长度为 160 位。
我们不会一次全部提供文件中的数据,因为某些文件非常大,无法一次全部放入内存中。 将文件分成小块将提高进程内存的效率。
查找哈希的源代码
# Python rogram to find the SHA-1 message digest of a file# importing the hashlib moduleimport hashlibdef hash_file(filename):""""This function returns the SHA-1 hashof the file passed into it"""# make a hash objecth = hashlib.sha1()# open file for reading in binary modewith open(filename,'rb') as file:# loop till the end of the filechunk = 0while chunk != b'':# read only 1024 bytes at a timechunk = file.read(1024)h.update(chunk)# return the hex representation of digestreturn h.hexdigest()message = hash_file("track1.mp3")print(message)
输出
633d7356947eec543c50b76a1852f92427f4dca9
在此程序中,我们以二进制模式打开文件。 哈希函数在hashlib模块中可用。 我们使用while循环循环到文件末尾。 到达最后时,我们得到空字节对象。
在每次迭代中,我们仅从文件中读取 1024 个字节(可以根据需要更改此值),并更新哈希函数。
最后,我们使用hexdigest()方法以十六进制表示形式返回摘要消息。
