How to Hash a File in Python?

In this article, you will learn how to How to Hash a File in Python. In Python hashing a file or a string is very easy by using a hashlib module. Hashlib module supports various hashing algorithms such as MD5, SHA-1, SHA-256, and may more.

Hashing is the process of producing a fixed-size string of characters that represents the input. This fixed-size string is known as the hash value, hash code, or digest.

  • It is important to consider factors such as security, speed, and collision resistance when selecting a hashing algorithm.
  • Hashing is a one-way process and it is not possible to reverse the hash value to recover the original input.
  • Collisions (two different inputs producing the same hash value) can occur for some hashing algorithms.
  • Salted hashing (adding a random string of characters to the input before hashing) is recommended for password storage

Hash a File in Python Using hashlib Module

import hashlib

filename = input("Enter the name of the file: ")

with open(filename, "rb") as f:
    bytes = f.read()  # read entire file as bytes

hash = hashlib.sha256(bytes).hexdigest()

print(f"The SHA256 hash of {filename} is: {hash}")

In this program, we import the hashlib module to compute the SHA256 hash of a file.

The program asks the user to enter the file’s name, reads the entire file as bytes, computes the hash using the sha256() function, and prints the hash in hexadecimal format using the hexdigest() function.

Ouput

C:\Users\user\tutcoach.com>python program.py
Enter the name of the file: C:\users\user\Desktop\51.jpg
The SHA256 hash of C:\users\user\Desktop\51.jpg is: affba018a199766380e466e469870d404171ad2aab2dcdb8a1fc5aa08f1e875e

Conclusion

Common hashing algorithms available are MD5, SHA-1, SHA-256, and SHA-512. When choosing a hashing algorithm for your project, you should consider the factors such as security, speed, and collision resistance

Leave a Comment