In this article, we have provided a python source code that can find the hash of a file and display it
Prerequisite topics to create this program.
- 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:
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)
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:
- WAP to find the average of list of numbers entered by the user
- WAP to print the sum of first n natural numbers
- Python Examples
- WAP to calculate the area of a circle and accepts radius from the user
- WAP to raise any number x to a Positive Power n
- Python RegEx
- WAP to Display Fibonacci Series
- Python Program to Check if a Number is Odd or Even
- How to Find Square Root in Python?
- Python Program to Solve Quadratic Equation