Python Program to Find Hash of File
In this example, we will write a python program to find the hash of a file. Hash is used in the cryptography to encrypt the content of a file. The output of the function is called the digest message. There are many hashing functions like MD5, SHA-1 etc. You can find the hash of a file using the hashlib library. Note that file sizes can be pretty big. It is best to use a buffer to load chunks and process them to calculate the hash of the file. You can take a buffer of any size. To better understand this example, make sure you have knowledge of the following tutorials:-
Let us write a program to find hash of a “hello.txt” file
import hashlib BUF_SIZE = 32768 # Read file in 32kb chunks md5 = hashlib.md5() sha1 = hashlib.sha1() with open('hello.txt', 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break md5.update(data) sha1.update(data) print("MD5: {0}".format(md5.hexdigest())) print("SHA1: {0}".format(sha1.hexdigest()))
The output of the program is:-
SHA1: 208cc699c87f7d1cbcd175115e7c04eec8292d2f