Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. import os
  2. from Crypto.Cipher import AES
  3. from Crypto.Hash import SHA256
  4. from Crypto import Random
  5.  
  6.  
  7. def encrypt(key, filename):
  8. chunksize = 64 * 1024
  9. outputFile = "(encrypted)" + filename
  10. filesize = str(os.path.getsize(filename)).zfill(16)
  11. IV = Random.new().read(16)
  12.  
  13. encryptor = AES.new(key, AES.MODE_CBC, IV)
  14.  
  15. with open(filename, 'rb') as infile:
  16. with open(outputFile, 'wb') as outfile:
  17. outfile.write(filesize.encode('utf-8'))
  18. outfile.write(IV)
  19.  
  20. while True:
  21. chunk = infile.read(chunksize)
  22.  
  23. if len(chunk) == 0:
  24. break
  25. elif len(chunk) % 16 != 0:
  26. chunk += b' ' * (16 - (len(chunk) % 16))
  27.  
  28. outfile.write(encryptor.encrypt(chunk))
  29.  
  30.  
  31. def decrypt(key, filename):
  32. chunksize = 64 * 1024
  33. outputFile = filename[11:]
  34.  
  35. with open(filename, 'rb') as infile:
  36. filesize = int(infile.read(16))
  37. IV = infile.read(16)
  38.  
  39. decryptor = AES.new(key, AES.MODE_CBC, IV)
  40.  
  41. with open(outputFile, 'wb') as outfile:
  42. while True:
  43. chunk = infile.read(chunksize)
  44.  
  45. if len(chunk) == 0:
  46. break
  47.  
  48. outfile.write(decryptor.decrypt(chunk))
  49. outfile.truncate(filesize)
  50.  
  51.  
  52. def getKey(password):
  53. hasher = SHA256.new(password.encode('utf-8'))
  54. return hasher.digest()
  55.  
  56.  
  57. def Main():
  58. choice = input("Would you like to (E)ncrypt or (D)ecrypt?: ")
  59. if choice == 'E' or choice == 'e':
  60. filename = input("File to encrypt: ")
  61. password = input("Password: ")
  62. encrypt(getKey(password), filename)
  63. print("Done.")
  64. elif choice == 'D' or choice == 'd':
  65. filename = input("File to decrypt: ")
  66. password = input("Password: ")
  67. decrypt(getKey(password), filename)
  68. print("Done.")
  69. else:
  70. print("No Option selected, closing...")
  71.  
  72.  
  73. if __name__ == '__main__':
  74. Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement