Guest User

Untitled

a guest
Sep 21st, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. from Crypto.PublicKey import RSA
  2. from Crypto.Random import get_random_bytes
  3. from Crypto.Cipher import AES, PKCS1_OAEP
  4.  
  5. class Encrypt:
  6.     def __init__(self):
  7.         self.key = RSA.generate(2048)
  8.  
  9.     def gen_public_key(self):
  10.         self.public_key = self.key.publickey().export_key()
  11.  
  12.         file_out = open("receiver.pem", "wb")
  13.         file_out.write(self.public_key)
  14.         file_out.close()
  15.  
  16.  
  17.     def gen_private_key(self):
  18.         private_key = self.key.export_key()
  19.  
  20.         file_out = open("private.pem", "wb")
  21.         file_out.write(private_key)
  22.         file_out.close()
  23.  
  24.  
  25.     def encode(self):
  26.         data = "I met aliens in UFO. Here is the map,I met aliens in UFO. Here is the mapI met aliens in UFO. Here is the map,I met aliens in UFO. Here is the mapI met aliens in UFO. Here is the map.".encode("utf-8")
  27.         file_out = open("encrypted_data.bin", "wb")
  28.  
  29.         recipient_key = RSA.import_key(open("receiver.pem").read())
  30.         session_key = get_random_bytes(16)
  31.  
  32.         # Encrypt the session key with the public RSA key
  33.         cipher_rsa = PKCS1_OAEP.new(recipient_key)
  34.         enc_session_key = cipher_rsa.encrypt(session_key)
  35.  
  36.         # Encrypt the data with the AES session key
  37.         cipher_aes = AES.new(session_key, AES.MODE_EAX)
  38.         ciphertext, tag = cipher_aes.encrypt_and_digest(data)
  39.         [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
  40.         file_out.close()
  41.  
  42.  
  43.     def decode(self):
  44.         file_in = open("encrypted_data.bin", "rb")
  45.         private_key = RSA.import_key(open("private.pem").read())
  46.         enc_session_key, nonce, tag, ciphertext = \
  47.             [file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1)]
  48.  
  49.         # Decrypt the session key with the private RSA key
  50.         cipher_rsa = PKCS1_OAEP.new(private_key)
  51.         session_key = cipher_rsa.decrypt(enc_session_key)
  52.  
  53.         # Decrypt the data with the AES session key
  54.         cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
  55.         data = cipher_aes.decrypt_and_verify(ciphertext, tag)
  56.         print(data.decode("utf-8"))
  57.  
  58.  
  59. if __name__ == "__main__":
  60.     e = Encrypt()
  61.  
  62.     # e.gen_public_key()
  63.     # e.encode()
  64.  
  65.     e.gen_private_key()
  66.     e.decode()
Advertisement
Add Comment
Please, Sign In to add comment