Validate SHA256 Checksums with Python

import tkinter as tk
from tkinter import filedialog, simpledialog, messagebox
import hashlib

def calculate_sha256(file_path):
    sha256_hash = hashlib.sha256()
    with open(file_path, "rb") as f:
        # Read and update hash string value in blocks of 4K
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
    return sha256_hash.hexdigest()

def verify_checksum():
    file_path = filedialog.askopenfilename(title="Select the file to check the SHA256 checksum on", filetypes=[("All Files", "*.*")])

    if file_path:
        # Prompt user for SHA256 checksum
        entered_checksum = simpledialog.askstring("Checksum Verification", "Enter SHA256 checksum:")

        # Calculate the SHA256 checksum of the selected file
        file_checksum = calculate_sha256(file_path)

        # Compare entered checksum with calculated checksum
        if entered_checksum == file_checksum:
            messagebox.showinfo("Verification Result", "Checksum verification successful. The file has not been tampered with.")
        else:
            messagebox.showerror("Verification Result", "Checksum verification failed. The file may have been tampered with.")
    else:
        messagebox.showinfo("File Selection", "File selection cancelled by the user.")

# Create the main application window
root = tk.Tk()
root.withdraw()  # Hide the main window

# Call the verify_checksum function
verify_checksum()

# Start the main loop
root.mainloop()

Leave a Reply

Your email address will not be published. Required fields are marked *