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()
- words = ["apple", "bagel", "car", "daring", "electronic", "fax", "gigantic", "honey", "ice", "journal",
- "kite", "laser", "mask", "new", "obelisk", "painter", "queen", "red", "satellite", "tokyo",
- "university", "vampire", "wiggly", "xylophone", "yoga", "zebra"]
- assert(len(words) == 26)
- def number_to_base(n, b):
- if n == 0:
- return [0]
- digits = []
- while n:
- digits.append(int(n % b))
- n //= b
- return digits[::-1]
- # 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()
- overall_hash_base26 = number_to_base(int(overall_hash, 16), len(words))
- overall_hash_mnemonic = ' '.join([words[i] for i in overall_hash_base26])
- root = tk.Tk()
- root.withdraw()
- # Show the hash to the user
- tk.messagebox.showinfo("File integrity", "SHA256 of files: \n{}\n\n{}".format(overall_hash, overall_hash_mnemonic))
- root.destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement