rsacryptor.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. # /usr/bin/env python3
  2. import os
  3. import datetime
  4. import time
  5. import sys
  6. from Crypto.PublicKey import RSA
  7. from Crypto.Cipher import PKCS1_OAEP, AES
  8. import os
  9. import getpass
  10. class Cryptor:
  11. def __init__(self):
  12. self.path = f"/home/{getpass.getuser()}/FileCryptor/"
  13. if os.path.exists(self.path):
  14. pass
  15. else:
  16. os.system("mkdir "+self.path)
  17. def encrypt(self, dataFile, publicKeyFile):
  18. '''
  19. use EAX mode to allow detection of unauthorized modifications
  20. '''
  21. # read data from file
  22. with open(dataFile, 'rb') as f:
  23. data = f.read()
  24. # convert data to bytes
  25. data = bytes(data)
  26. # read public key from file
  27. with open(publicKeyFile, 'rb') as f:
  28. publicKey = f.read()
  29. # create public key object
  30. key = RSA.import_key(publicKey)
  31. sessionKey = os.urandom(16)
  32. # encrypt the session key with the public key
  33. cipher = PKCS1_OAEP.new(key)
  34. encryptedSessionKey = cipher.encrypt(sessionKey)
  35. # encrypt the data with the session key
  36. cipher = AES.new(sessionKey, AES.MODE_EAX)
  37. ciphertext, tag = cipher.encrypt_and_digest(data)
  38. []
  39. # save the encrypted data to file
  40. [fileName, fileExtension] = dataFile.split('.')
  41. encryptedFile = fileName + '.' + fileExtension
  42. with open(encryptedFile, 'wb+') as f:
  43. [f.write(x) for x in (encryptedSessionKey, cipher.nonce, tag, ciphertext)]
  44. print('Encrypted file saved to ' + encryptedFile)
  45. def decrypt(self, dataFile, privateKeyFile):
  46. '''
  47. use EAX mode to allow detection of unauthorized modifications
  48. '''
  49. # read private key from file
  50. with open(privateKeyFile, 'rb') as f:
  51. privateKey = f.read()
  52. # create private key object
  53. key = RSA.import_key(privateKey)
  54. # read data from file
  55. with open(dataFile, 'rb') as f:
  56. # convert data to bytes
  57. # read the session key
  58. encryptedSessionKey, nonce, tag, ciphertext = [f.read(x) for x in (key.size_in_bytes(), 16, 16, -1)]
  59. # decrypt the session key
  60. cipher = PKCS1_OAEP.new(key)
  61. sessionKey = cipher.decrypt(encryptedSessionKey)
  62. # decrypt the data with the session key
  63. cipher = AES.new(sessionKey, AES.MODE_EAX, nonce)
  64. data = cipher.decrypt_and_verify(ciphertext, tag)
  65. # save the decrypted data to file
  66. [fileName, fileExtension] = dataFile.split('.')
  67. decryptedFile = fileName + '.' + fileExtension
  68. with open(decryptedFile, 'wb') as f:
  69. f.write(data)
  70. print('Decrypted file saved to ' + decryptedFile)
  71. def genKey(self,nameFile):
  72. key = RSA.generate(2048)
  73. privateKey = key.export_key()
  74. publicKey = key.publickey().export_key()
  75. with open(self.path+"private_" + nameFile + ".pem", 'wb+') as f:
  76. f.write(privateKey)
  77. # save public key to file
  78. with open(self.path+"public_" + nameFile + ".pem", 'wb+') as f:
  79. f.write(publicKey)
  80. print("Keys saved in "+self.path)
  81. return [self.path+"private_" + nameFile + ".pem",self.path+"public_" + nameFile + ".pem"]
  82. CRYPTOR = Cryptor()
  83. def clear_screen():
  84. os.system('clear')
  85. def commands():
  86. print("1:Encrypt file")
  87. print("2:Decrypt file")
  88. print("3:Genereate standalone pair keys (pub/private)")
  89. print("4:About")
  90. print("0:Quit")
  91. def logo():
  92. print("╭━━━┳━━━┳━━━┳━━━┳╮╱╱╭┳━━━┳━━━━┳━━━┳━━━╮")
  93. print("┃╭━╮┃╭━━┫╭━╮┃╭━╮┃╰╮╭╯┃╭━╮┃╭╮╭╮┃╭━╮┃╭━╮┃")
  94. print("┃┃╱┃┃╰━━┫┃╱╰┫╰━╯┣╮╰╯╭┫╰━╯┣╯┃┃╰┫┃╱┃┃╰━╯┃")
  95. print("┃╰━╯┃╭━━┫┃╱╭┫╭╮╭╯╰╮╭╯┃╭━━╯╱┃┃╱┃┃╱┃┃╭╮╭╯")
  96. print("┃╭━╮┃╰━━┫╰━╯┃┃┃╰╮╱┃┃╱┃┃╱╱╱╱┃┃╱┃╰━╯┃┃┃╰╮")
  97. print("╰╯╱╰┻━━━┻━━━┻╯╰━╯╱╰╯╱╰╯╱╱╱╱╰╯╱╰━━━┻╯╰━╯")
  98. def encrypt():
  99. clear_screen()
  100. file = input("Enter full path to file:")
  101. print("Select:\n 1:Use exist public key \n 2:Generate new keys")
  102. q = int(input("Select:"))
  103. if q==1:
  104. clear_screen()
  105. path_to_key = input("Enter full path to public key:")
  106. clear_screen()
  107. CRYPTOR.encrypt(file,path_to_key)
  108. time.sleep(5)
  109. else:
  110. keys = CRYPTOR.genKey(str(datetime.date.today()))
  111. clear_screen()
  112. CRYPTOR.encrypt(file,keys[1])
  113. time.sleep(5)
  114. def decrypt():
  115. clear_screen()
  116. file = input("Enter full path to file:")
  117. key = input("Enter full path to private key:")
  118. CRYPTOR.decrypt(file,key)
  119. time.sleep(5)
  120. def genkey():
  121. clear_screen()
  122. CRYPTOR.genKey(str(datetime.date.today()))
  123. print("Keys generated in your home folder.")
  124. time.sleep(5)
  125. def about():
  126. clear_screen()
  127. logo()
  128. print("This program created for encryption/decryption files with AES.\nIMPORTANT: if you will try encrypt photos (.png and etc.) you can see preview of this file.")
  129. print("Created by Ebobalik. URL:https://notabug.org/Ebobalik")
  130. input()
  131. def main_loop():
  132. clear_screen()
  133. while True:
  134. logo()
  135. commands()
  136. query = int(input("Select:"))
  137. match query:
  138. case 0:
  139. break
  140. case 1:
  141. encrypt()
  142. case 2:
  143. decrypt()
  144. case 3:
  145. genkey()
  146. case 4:
  147. about()
  148. clear_screen()
  149. if __name__=="__main__":
  150. params = sys.argv
  151. params.pop(0)
  152. if len(params) == 1:
  153. if params[0]=="-G":
  154. main_loop()
  155. if params[0]=="--help" or params[0]=="-H":
  156. logo()
  157. print("Keys for usage: \n-E: encrypt file. \n-D: decrypt file. \n-H or --help: show this message. \n-k: path to private or public keys. For encryption file you should use public key. For decryption - private key.")
  158. elif len(params)>1:
  159. if params[0]=="-D":
  160. if len(params)==4:
  161. CRYPTOR.decrypt(params[1],params[3])
  162. else:
  163. print("Incorrect command. Run with key --help or -H")
  164. if params[0]=="-E":
  165. if len(params)==4:
  166. CRYPTOR.decrypt(params[1],params[3])
  167. elif len(params)==2:
  168. keys = CRYPTOR.genKey(str(datetime.date.today()))
  169. CRYPTOR.encrypt(params[1],keys[1])
  170. else:
  171. print("Incorrect command. Run with key --help or -H")
  172. if params[0]=="-GSK":
  173. CRYPTOR.genKey("StandaloneKeys")