Advertisement
Guest User

hash.py - Dec 9, 2018

a guest
Dec 9th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 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. words = ["apple", "bagel", "car", "daring", "electronic", "fax", "gigantic", "honey", "ice", "journal",
  21.          "kite", "laser", "mask", "new", "obelisk", "painter", "queen", "red", "satellite", "tokyo",
  22.          "university", "vampire", "wiggly", "xylophone", "yoga", "zebra"]
  23.  
  24. assert(len(words) == 26)
  25.  
  26. def number_to_base(n, b):
  27.     if n == 0:
  28.         return [0]
  29.     digits = []
  30.     while n:
  31.         digits.append(int(n % b))
  32.         n //= b
  33.     return digits[::-1]
  34.  
  35. # Get the directory that the script is in, not the current working directory
  36. script_dir = os.path.dirname(os.path.abspath(__file__))
  37.  
  38. # Hash every file in the current directory and all subdirectories
  39. hashes = []
  40. for subdir, dirs, files in os.walk(script_dir):
  41.     for file in files:
  42.         # Include the script in the hash, to ensure that the code remains unchanged
  43.         path = os.path.join(subdir, file)
  44.         hashes.append(hash_file(path))
  45.  
  46. overall_hasher = hashlib.sha256()
  47. # Sort the hashes so that the order the files were processed in is irrelevant
  48. overall_hasher.update(b''.join(sorted(hashes)))
  49. # Use a Merkle-style hash to compute the overall hash
  50. # See https://en.wikipedia.org/wiki/Merkle_tree
  51. overall_hash = overall_hasher.hexdigest()
  52.  
  53. overall_hash_base26 = number_to_base(int(overall_hash, 16), len(words))
  54. overall_hash_mnemonic = ' '.join([words[i] for i in overall_hash_base26])
  55.  
  56. root = tk.Tk()
  57. root.withdraw()
  58.  
  59. # Show the hash to the user
  60. tk.messagebox.showinfo("File integrity", "SHA256 of files: \n{}\n\n{}".format(overall_hash, overall_hash_mnemonic))
  61.  
  62. root.destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement