Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
HowToDoInJava
  • Java
  • Spring AI
  • Spring Boot
  • Hibernate
  • JUnit 5
  • Interview

Python hashlib

Learn to calculate the Hash of a file in Python, with examples. It is also called the file checksum or digest. A checksum hash is an encrypted sequence of characters obtained after applying certain algorithms and manipulations on user-provided content. Read More: File checksum in Java 1. Hash …

Lokesh Gupta

July 6, 2021

Python Modules
Java Hashing, Python Basics
Python

Learn to calculate the Hash of a file in Python, with examples. It is also called the file checksum or digest. A checksum hash is an encrypted sequence of characters obtained after applying certain algorithms and manipulations on user-provided content.

Read More: File checksum in Java

1. Hash Algorithms

Hash functions are cryptographic functions that produces a fixed length/format encoded output for any given input. For any given input, a given hash function will always generate the same output – no matter how many times we execute the hash function.

Hash functions are generally applied over passwords and store then encrypted strings in database. In this way, user password is never stored in any plain text form in the system and makes security robust.

Similarly, when want to transfer a secure file to another host – we also pass the file digest information so remote host can generate the digest from transferred file and match with digest sent from source host. It both matches, file content has not been tempered.

we can read more about individual hashing algorithms in detail. In this post, we will only see the examples of various hashing algorithms.

2. Python File Hash Algorithms

We can use the hashlib module which provides necessary methods for generating various kind of hashes.

  • To know all available algorithms provided by this module, use its algorithms_guaranteed property.
  • The update() function to append byte message to the secure hash value.
  • The digest() or hexdigest() functions we can get the secure hash.
import hashlib

print(hashlib.algorithms_guaranteed)

Program output.

{'shake_256', 'sha1', 'blake2s', 'sha3_224', 'sha512', 
 'sha3_256', 'sha224', 'sha256', 'sha3_384', 
 'sha384', 'blake2b', 'sha3_512', 'shake_128', 'md5'}

3. Pyhton File Hash Examples

Lets see few examples to generate hash of a given file in Python.

Example 1: Find SHA256 Hash of a File in Python

Python program to find the SHA256 hash of a given file.

import hashlib # hashlib module
import os.path # For file handling
from os import path

def hash_file(filename):

	if path.isfile(filename) is False:
		raise Exception("File not found for hash operation") 

	# make a hash object
	h_sha256 = hashlib.sha256()

	# open file for reading in binary mode
	with open(filename,'rb') as file:

		# read file in chunks and update hash
		chunk = 0
		while chunk != b'':
			chunk = file.read(1024)	
			h_sha256.update(chunk)

	# return the hex digest
	return h_sha256.hexdigest()

####### Example Usage
message = hash_file("Python")
print(message)

Program output.

8964ed69cac034a6bc88ad33089500b6a26a62f19e1574f2f8fbfddeb9a30667

Example 2: Find SHA Hash of a File in Python (Not recommended)

Python program to find the SHA1 hash of a given file.

import hashlib # hashlib module
import os.path # For file handling
from os import path

def hash_file(filename):

	if path.isfile(filename) is False:
		raise Exception("File not found for hash operation") 

	# make a hash object
	h = hashlib.sha1()

	# open file for reading in binary mode
	with open(filename,'rb') as file:

		# read file in chunks and update hash
		chunk = 0
		while chunk != b'':
			chunk = file.read(1024)	
			h.update(chunk)

	# return the hex digest
	return h.hexdigest()

####### Example Usage
message = hash_file("Python")
print(message)

Program output.

498fd2d318447f9d0fac30c6e0997c03861c679b

Example 3: Find MD5 Hash of a File in Python (Not recommended)

Python program to find MD5 SHA1 hash of a given file.

import hashlib # hashlib module
import os.path # For file handling
from os import path

def hash_file(filename):

	if path.isfile(filename) is False:
		raise Exception("File not found for hash operation") 

	# make a hash object
	md5_h = hashlib.md5()

	# open file for reading in binary mode
	with open(filename,'rb') as file:

		# read file in chunks and update hash
		chunk = 0
		while chunk != b'':
			chunk = file.read(1024)	
			md5_h.update(chunk)

	# return the hex digest
	return md5_h.hexdigest()

####### Example Usage
message = hash_file("Python")
print(message)

Program output.

ee6dcaf64b270667125a33f9b7bebb75

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Python Flow Control

  • Python if…else
  • Python for Loop
  • Python while Loop
  • Python break
  • Python continue
  • Python pass

Python Datatypes

  • Python Integer
  • Python String
  • Python List
  • Python Tuple
  • Python Set
  • Python Dictionary
  • Python OrderedDict
  • Python Priority Queue

Python Modules

  • Python Bcrypt
  • Python Hashlib
  • Python Httplib2
  • Python JSON

Python Advanced Topics

  • Python CSV Files
  • Building a Recommendation System

Python Reference

  • Built-in Functions
  • String Functions

Table of Contents

  • 1. Hash Algorithms
  • 2. Python File Hash Algorithms
  • 3. Pyhton File Hash Examples
      • Example 1: Find SHA256 Hash of a File in Python
      • Example 2: Find SHA Hash of a File in Python (Not recommended)
      • Example 3: Find MD5 Hash of a File in Python (Not recommended)
Photo of author

Lokesh Gupta

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter Portfolio

Previous

Python String count()

Next

Python bcrypt – Hash a Password with bcrypt

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

OOP

Regex

Maven

Logging

TypeScript

Python

Meta Links

About Us

Advertise

Contact Us

Privacy Policy

Our Blogs

REST API Tutorial

Follow On:

  • Github
  • LinkedIn
  • Twitter
  • Facebook
Copyright © 2026 | Sitemap