Advertisement
manick69

Untitled

Mar 22nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 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. #Encryption of files
  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. #Decryption of files
  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. def getKey(password):
  52.     hasher = SHA256.new(password.encode('utf-8'))
  53.     return hasher.digest()
  54.  
  55. def Main():
  56.     choice = input("Would you like to (E)ncrypt or (D)ecrypt?: ")
  57.  
  58.     if choice == 'E' or choice == 'e':
  59.         filename = input("File to encrypt: ")
  60.         password = input("Password: ")
  61.         encrypt(getKey(password), filename)
  62.     print("Done.")
  63.         elif choice == 'D' or choice == 'd':
  64.             filename = input("File to decrypt: ")
  65.             password = input("Password: ")
  66.             decrypt(getKey(password), filename)
  67.         print("Done.")
  68.     else:
  69.         print("No Option selected, closing...")
  70.  
  71. if __name__ == '__main__':
  72.     Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement