Hashing a File in Python

Python Program to Hash a File, Hashing Algorithm in Python

#Find hash of file in python

#importing sys and hashlib modules
import sys
import hashlib

BUF_SIZE = 32768 # Read file in 32kb chunks
#creating the hash objects
md5 = hashlib.md5()
sha1 = hashlib.sha1()
#open the file to read
with open('code.cpp', 'rb') as f:

while True:
   data = f.read(BUF_SIZE)
   if not data:
      Break
#update the hash
   md5.update(data)
   sha1.update(data)
#get the hexadecimal digest of the hash
print("MD5: {0}".format(md5.hexdigest()))
print("SHA1: {0}".format(sha1.hexdigest()))

Output:

MD5: 7481a578b20afc6979148a6a5f5b408d
SHA1: f7187ed8b258baffcbff2907dbe284f8f3f8d8c6

About The Author

Leave a Reply