Python Program to Find Hash of File
A hash of a file, also known as a message digest or digital fingerprint, is a unique string of characters that is generated by applying a mathematical algorithm to the contents of a file. This hash value is typically much shorter than the actual file, and it serves as a kind of digital signature that can be used to verify the integrity and authenticity of the file.
Python Code :
The below Python program finds the hash of a file:
import hashlib # Open the file in read-only binary mode with open('file.txt', 'rb') as file: # Create a hash object hasher = hashlib.sha256() # Loop through the file one chunk at a time for chunk in iter(lambda: file.read(4096), b''): # Update the hash object with the current chunk hasher.update(chunk) # Get the hexadecimal representation of the hash hash_hex = hasher.hexdigest() # Print the hash print(hash_hex)
In this program, we use the hashlib module to create a hash object, which we then update with chunks of the file using a loop.
We read the file one chunk at a time to conserve memory, since reading the whole file into memory at once could be problematic for large files. Finally, we get the hexadecimal representation of the hash using the hexdigest() method, and print it to the console.
Replace ‘file.txt’ with the path to the file you want to hash, and you should be good to go!