Using Python to compute a MD5 Hash

This entry is part 3 of 4 in the series MD 5 Calculation

Here some Python code to calculate the MD5 hash for a given file:

# from http://www.pythoncentral.io/hashing-files-with-python/
import hashlib
 
hasher = hashlib.md5()
with open('e:/Mappe1.xlsx', 'rb') as afile:
    buf = afile.read()
    hasher.update(buf)
print(hasher.hexdigest())

Here the final script that provides the same functionality as the Powershell script I posted earlier today:

# http://www.pythoncentral.io/hashing-files-with-python/
import hashlib
import os
import codecs
 
hasher = hashlib.md5()
 
def calcHash(filename):
	print("Filename:   " + filename)
	with open(filename, 'rb') as afile:
		buf = afile.read()
		hasher.update(buf)
		print("Calculated: " + hasher.hexdigest())
		md5file = (os.path.splitext(filename)[0]) + ".md5"
		givenMD5 = codecs.open(md5file, "r", "utf-8-sig")
		print("Provided:   " + str(givenMD5.read()).lower())
 
calcHash("e:/Mappe1.xlsx")

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Series Navigation<< Using Powershell to create MD5 filesCreating MD5 files with Python >>