Python Program to find Hash of File

Posted in

Python Program to find Hash of File
vinaykhatri

Vinay Khatri
Last updated on February 11, 2025

In this article, we have provided a python source code that can find the hash of a file and display it

Prerequisite Python Program to find Hash of File

  • Python Functions
  • Python user-defined functions
  • Python Modules
  • Python hashlib library
  • Python File I/O

A hash function accepts the data and returns a fixed-length bit string. Hash functions mostly used in cryptography and authentications. There are various hashing functions such as MD5, SHA-1, etc. In python, we have an inbuilt library known as hashlib which use the SHA-1 hashing algorithms and provide a 160 bits long digest message, a digest message is the string output of the hash function. We can pass any type of data to the hash function.

Python Program to find Hash of File

Python Code

import hashlib

def find_hash(filename):
    # Create a hash Object

   h_o = hashlib.sha1()

   # open the data in binary mode
   with open(filename,'rb') as file:

       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk = file.read(1024)
           h_o.update(chunk)

   # return the hex representation of digest
   return h_o.hexdigest()

message = find_hash("image.jpg")
print(message)

Output:

69b7602879cb723fa7ba0d1c709f351a7610345b

Behind the Code

Here we have created a hash function by name find_hash() which accept the file as an argument. Inside the function using the with open(filename,'rb') as file statement we open the file in binary mode and using the while chunk != b'': statement looped through its binary data and with each iteration of the while loop the hash object h_o read the 1024 bytes of data and update the hash function. Once the while loop ends we return the hash message in hexadecimal representation.

People are also reading:

Leave a Comment on this Post

0 Comments