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:-

According to Wikipedia, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function which takes an input and produces a 160-bit (20-byte) hash value known as a message digest – typically rendered as a hexadecimal number, 40 digits long. Learn more about SHA-1 here.

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 =
       if not data:

    print("MD5: {0}".format(md5.hexdigest()))
    print("SHA1: {0}".format(sha1.hexdigest()))

The output of the program is:-

MD5: f6ff56b7e6ecf3ca935a76daeab08b73
SHA1: 208cc699c87f7d1cbcd175115e7c04eec8292d2f
SHARE Python Program to Find Hash of File

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *