English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced Python knowledge

Python reference manual

Python program to find the hash value of a file

Python instance大全

In this article, you will learn to find the hash value of a file and display it.

To understand this example, you should know the followingPython programmingTopic:

The hash function takes an arbitrary amount of data and returns a fixed-length bit string. The output of the function is called a message digest.

They are widely used in cryptography for authentication. There are many hash functions, such as MD5,SHA-1and so on. Please refer to this page for more information aboutHash functions in cryptographyMore information.

In this example, we will demonstrate how to hash a file. We will use SHA-1hash algorithm. SHA-1The length of the digest is160 bits.

We will not provide all the data in the file at once because some files are very large and cannot be put into memory all at once. Splitting the file into chunks will improve the efficiency of the process memory.

Find the source code of the hash

# Python program to find the SHA of a file1Message Digest
# Import the hashlib module
import hashlib
def hash_file(filename):
   """This function returns SHA"-1Hash
    passing the file """
   # Create a hash object
   h = hashlib.sha1()
   # Open the file in binary read mode
   with open(filename, 'rb') as file:
       # Loop until the end of the file
       chunk = 0
       while chunk != b''
           # Read once only1024bytes
           chunk = file.read(1024)
           h.update(chunk)
   # Return the hexadecimal representation of the digest
   return h.hexdigest()
message = hash_file("track"1.mp3")
print(message)

Output result

633d7356947eec543c50b76a1852f92427f4dca9

In this program, we open the file in binary mode. Hash functions are available in the hashlib module. We use a while loop until the end of the file. When we reach the end, we get an empty byte object.

In each iteration, we only read from the file1024bytes (this value can be changed as needed) and update the hash function.

Finally, we use the hexdigest() method to return the digest message in hexadecimal format.

Python instance大全