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

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Programme Python pour trouver la valeur de hachage d'un fichier

Python example大全

Dans cet article, vous apprendrez à trouver la valeur de hachage d'un fichier et à la montrer.

Pour comprendre cet exemple, vous devriez comprendre ce qui suitProgrammation PythonSujet :

Les fonctions de hachage prennent une quantité quelconque de données et renvoient une chaîne de bits de longueur fixe. La sortie de la fonction est appelée message de résumé.

They are widely used in cryptography for authentication. There are many hash functions, such as MD5,SHA-1etc. Please refer to this page to learn more 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 placed in 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 only once1024bytes
           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 example大全