Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hashlib
- import os
- import tkinter as tk
- import tkinter.messagebox
- # Cryptographic hashes are used to determine data integrity. A key feature of hashes
- # is that they are designed to be collision resistant: nobody should be able to find
- # two different input values that result in the same output hash.
- def hash_file(file_name):
- BLOCKSIZE = 65536
- # Use the SHA256 hashing algorithm
- hasher = hashlib.sha256()
- with open(file_name, 'rb') as afile:
- buf = afile.read(BLOCKSIZE)
- while len(buf) > 0:
- hasher.update(buf)
- buf = afile.read(BLOCKSIZE)
- return hasher.digest()
- # Get the directory that the script is in, not the current working directory
- script_dir = os.path.dirname(os.path.abspath(__file__))
- # Hash every file in the current directory and all subdirectories
- hashes = []
- for subdir, dirs, files in os.walk(script_dir):
- for file in files:
- # Include the script in the hash, to ensure that the code remains unchanged
- path = os.path.join(subdir, file)
- hashes.append(hash_file(path))
- overall_hasher = hashlib.sha256()
- # Sort the hashes so that the order the files were processed in is irrelevant
- overall_hasher.update(b''.join(sorted(hashes)))
- # Use a Merkle-style hash to compute the overall hash
- # See https://en.wikipedia.org/wiki/Merkle_tree
- overall_hash = overall_hasher.hexdigest()
- root = tk.Tk()
- root.withdraw()
- # Show the hash to the user
- tk.messagebox.showinfo("File integrity", "SHA256 of files: \n{}".format(overall_hash))
- root.destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement