Examples of Cryptography with Python Hashlib


Cryptography plays a critical role in digital communication and data security today. The confidentiality, integrity, and authenticity of communications are crucial in modern computing environments. Therefore, using secure data processing techniques and tools is vital to ensuring information security.

Python offers various libraries for performing cryptographic operations, one of which is the hashlib library. Hashlib is a Python library used for cryptographic operations such as data integrity checks, password hashing, and generating security codes.

In this article, we will explore cryptographic operations with the hashlib library. We will demonstrate how the hashlib library can be used and in which scenarios it can be beneficial. The aim is to help anyone with a basic understanding of Python to grasp how cryptographic operations can be performed using the hashlib library, covering an essential area used to ensure data integrity. The hashlib library in Python can be used for cryptographic operations such as data integrity checks, password hashing, and generating security codes. In this article, we will explore several examples related to cryptography using the hashlib library.

What is Hashlib and Why Use It?

Hashlib is one of Python’s standard libraries that provides various hash algorithms (MD5, SHA-1, SHA-256, etc.). Hash algorithms are used to create a unique digest of data. These digests can be used in many areas, such as verifying data integrity, password authentication, and ensuring data integrity. (Linux: A Cheat Sheet to Essential Commands)

The Hashlib library is a widely used tool in secure data processing applications. It plays an important role, especially in security-related operations like password hashing, file integrity checks, and data integrity verification.

In this article, by understanding the use of the hashlib library, we aim to enable Python users to perform cryptographic operations.

1 . Calculating MD5 Hash:

MD5 produces a 128-bit digest. However, due to various security vulnerabilities, MD5 is generally no longer considered secure.

import hashlib

data = b"This is sample data."
md5_hash = hashlib.md5(data).hexdigest()

print("MD5 Hash Value:", md5_hash)
2. Password Hasher: 

You can create an application that securely hashes passwords using hashlib obtained from users. This way, you can keep users’ passwords secure.

import hashlib

def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

password = input("Enter your password: ")
hashed_password = hash_password(password)
print("Hashed Password:", hashed_password)
3. File Heasher

You can calculate the hash value of a file specified by the user (for example, a text file or an image file).

import hashlib

def hash_file(filename):
    hasher = hashlib.sha256()
    with open(filename, 'rb') as f:
        while True:
            data =  # Read in 64 KB blocks
            if not data:
    return hasher.hexdigest()

filename = input("Enter the filename: ")
hashed_file = hash_file(filename)
print("Hashed File:", hashed_file)
4. Data Integrity Verifier

You can calculate the hash value of a file to check data integrity and then verify whether the file has been modified.

import hashlib

def calculate_hash(data):
    return hashlib.sha256(data.encode()).hexdigest()

original_data = "Original data here"
original_hash = calculate_hash(original_data)

# Simulating data change
modified_data = "Modified data here"
modified_hash = calculate_hash(modified_data)

if original_hash == modified_hash:
    print("Data integrity verified. The data has not been modified.")
    print("Data integrity compromised. The data has been modified.")
5. Email Authenticator

You can create an application that checks if the email and password provided by the user are correct. You can compare the hashed password with the hash value stored in the database

import hashlib

def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

def authenticate(email, password, stored_password):
    if hash_password(password) == stored_password:
        return True
        return False

# User information and hash retrieved from the database
email = ""
password = "password123"
stored_password = "3b0e7306c3d9e6452540b44763d2af60c3fe3d11b622ec89e580f0b5f8d85a8d"  # Hashed password from the database

# Authentication
if authenticate(email, password, stored_password):
    print("Authentication successful.")
    print("Authentication failed. Invalid email or password.")
6. SHA-256 Security Code Generator

You can generate SHA-256-based security codes for specific data

import hashlib

def generate_security_code(data):
    return hashlib.sha256(data.encode()).hexdigest()[:8]  # Take the first 8 characters

data = input("Enter data: ")
security_code = generate_security_code(data)
print("Security Code:", security_code)

7.Cryptographic Security

You can use hashlib to store user passwords securely. You can hash user passwords and store them along with an appropriate salt. (Assessing Password Strength with Machine Learning in Python)

import hashlib
import secrets

def hash_password(password, salt=None):
    if salt is None:
        salt = secrets.token_hex(16)  # Generate a 16-byte random salt
    hashed_password = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)
    return hashed_password, salt

def verify_password(stored_password, stored_salt, provided_password):
    hashed_password, _ = hash_password(provided_password, stored_salt)
    return hashed_password == stored_password

# User registration
user_password = "password123"
hashed_password, salt = hash_password(user_password)

# Password verification
if verify_password(hashed_password, salt, user_password):
    print("Password is correct.")
    print("Password is incorrect.")


(Beginning Your Journey in Programming and Cybersecurity – Navigating the Digital Future)

Python’s hashlib library is a powerful tool for performing cryptographic operations. It supports both old algorithms like MD5 and more secure hash algorithms like SHA-256. These examples demonstrate the use of hashlib and emphasize its importance as a tool for ensuring data security in everyday applications.

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.