1 min read

File Hash Calculator

This utility calculates the MD5, SHA1, and SHA256 hashes of a given file. It reads the file in binary mode and processes it in chunks, ensuring it can handle large files without using excessive memory.

Modules Used:

  • hashlib: To calculate secure hashes and message digests.
  • argparse: To handle command-line arguments.

The Code

Save this as hasher.py.

import hashlib
import argparse
import sys
import os

def calculate_hashes(file_path):
    if not os.path.exists(file_path):
        print(f"Error: File '{file_path}' not found.")
        return

    # Initialize hash objects
    md5 = hashlib.md5()
    sha1 = hashlib.sha1()
    sha256 = hashlib.sha256()

    print(f"Calculating hashes for '{file_path}'...")

    try:
        with open(file_path, 'rb') as f:
            # Read in chunks (e.g., 64KB) to handle large files efficiently
            while True:
                chunk = f.read(65536)
                if not chunk:
                    break

                # Update all hashers with the chunk
                md5.update(chunk)
                sha1.update(chunk)
                sha256.update(chunk)

        print("-" * 70)
        print(f"{'Algorithm':<10} | {'Hash'}")
        print("-" * 70)
        print(f"{'MD5':<10} | {md5.hexdigest()}")
        print(f"{'SHA1':<10} | {sha1.hexdigest()}")
        print(f"{'SHA256':<10} | {sha256.hexdigest()}")
        print("-" * 70)

    except PermissionError:
        print(f"Error: Permission denied reading '{file_path}'.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="File Hash Calculator")
    parser.add_argument("file", help="Path to the file")

    args = parser.parse_args()

    calculate_hashes(args.file)

Usage

python hasher.py my_installer.exe

programming/python/python