How to Find Hash of File using Python?

PythonProgramming

You can find the hash of a file using the hashlib library. Note that file sizes can be pretty big. Its 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.

Example

import sys
import hashlib

BUF_SIZE = 32768 # Read file in 32kb chunks
md5 = hashlib.md5()
sha1 = hashlib.sha1()
with open('program.cpp', '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()))

Output

This will give the output

MD5: 7481a578b20afc6979148a6a5f5b408d
SHA1: f7187ed8b258baffcbff2907dbe284f8f3f8d8c6
raja
Published on 20-Apr-2018 08:00:57
Advertisements