Skip to content

Calculating File Hashes with PowerShell and Python

Published: at 12:34 AM

Overview

This guide provides detailed instructions for calculating file hashes on Windows using PowerShell and Python. You will learn how to compute checksums/file hashes for file integrity verification.

Using PowerShell

To calculate the file hash on Windows using PowerShell, use the following command:

Get-FileHash <filename>

Replace <filename> with the path to your file.

Using Python

Here’s a Python script to calculate the SHA256 hash of a file. This script also writes the file list with its hash to a markdown file. Make sure to add the appropriate handler to your .htaccess file.

.htaccess

AddHandler cgi-script .py .pl .cgi

Python Script

#!/usr/bin/python
import os
import hashlib
import sys

# Function to calculate the SHA256 hash of a file
def calculate_hash(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()

print("Content-type: text/html\n\n")
print("<html><head>")
print("<title>CGI Test</title>")
print("</head><body>")

# Define the directory to scan
directory = 'my_directory'
# Define the markdown file to write to
markdown_file = 'file_list.md'

print("<p>Python version:"+sys.version+"</p>")
print("<pre>")

# Open the markdown file for writing
with open(markdown_file, 'w') as f:
    # Write the header for the markdown file
    f.write("# File List\n\n")
    f.write("| File Name | Size (bytes) | Hash (SHA256) |\n")
    f.write("| --- | --- | --- |\n")

    # Loop through all files in the given directory
    for file_name in os.listdir(directory):
        file_path = os.path.join(directory, file_name)
        if os.path.isfile(file_path):
            print(file_name)
            file_size = os.path.getsize(file_path)
            print(file_size)
            file_hash = calculate_hash(file_path)
            print(file_hash)

            # Write the file details to the markdown file
            f.write('| %s | %s | %s |\n' % (file_name, file_size, file_hash))

print("</pre>")
print("<p>Markdown file 'file_list.md' has been created.</p>")
print("</body></html>")

Make sure to adjust the directory paths and other variables as needed for your specific use case.


Previous Post
Running a simple Python HTTPServer app on a Server
Next Post
Running SQL Server in Docker