Advertisement
Guest User

hash.py

a guest
Nov 16th, 2018
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. import hashlib
  2. import os
  3. import tkinter as tk
  4. import tkinter.messagebox
  5.  
  6. # Cryptographic hashes are used to determine data integrity. A key feature of hashes
  7. # is that they are designed to be collision resistant: nobody should be able to find
  8. # two different input values that result in the same output hash.
  9. def hash_file(file_name):
  10.     BLOCKSIZE = 65536
  11.     # Use the SHA256 hashing algorithm
  12.     hasher = hashlib.sha256()
  13.     with open(file_name, 'rb') as afile:
  14.         buf = afile.read(BLOCKSIZE)
  15.         while len(buf) > 0:
  16.             hasher.update(buf)
  17.             buf = afile.read(BLOCKSIZE)
  18.     return hasher.digest()
  19.  
  20. # Get the directory that the script is in, not the current working directory
  21. script_dir = os.path.dirname(os.path.abspath(__file__))
  22.  
  23. # Hash every file in the current directory and all subdirectories
  24. hashes = []
  25. for subdir, dirs, files in os.walk(script_dir):
  26.     for file in files:
  27.         # Include the script in the hash, to ensure that the code remains unchanged
  28.         path = os.path.join(subdir, file)
  29.         hashes.append(hash_file(path))
  30.  
  31. overall_hasher = hashlib.sha256()
  32. # Sort the hashes so that the order the files were processed in is irrelevant
  33. overall_hasher.update(b''.join(sorted(hashes)))
  34. # Use a Merkle-style hash to compute the overall hash
  35. # See https://en.wikipedia.org/wiki/Merkle_tree
  36. overall_hash = overall_hasher.hexdigest()
  37.  
  38. root = tk.Tk()
  39. root.withdraw()
  40.  
  41. # Show the hash to the user
  42. tk.messagebox.showinfo("File integrity", "SHA256 of files: \n{}".format(overall_hash))
  43.  
  44. root.destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement