I'm working on a project in which I'm going to encrypt some files. I already have an AES function implemented, and now I'm implementing an RSA portion. On the AES part, I created a new key every time I was going to encrypt a new file, even if the password was the same by using different salts. To recover said passwors, I needed to hash together a known password and salt. Should I do the same with RSA public and private keys? If so, could I apply the approach I used on AES keys to the RSA keys? Or shoul my approach be different?
This is how I generate my RSA keys:
from Crypto.PublicKey import RSA
class RsaKeyGenerator:
def __index__(self):
self.__key = RSA.generate(2048)
def generate_public_key(self):
return self.__key.publickey().exportKey()
def generate_private_key(self, password):
return self.__key.exportKey(passphrase=password, pkcs=8, protection="scryptAndAES128-CBC")
This is how I handle the encryption/decryption process:
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import PKCS1_OAEP, AES
class RsaCrypto:
def __init__(self, public_key):
self.public_key = RSA.import_key(open(public_key, 'rb').read())
self.__cipher_rsa = PKCS1_OAEP.new(self.public_key)
self.__session_key = get_random_bytes(16)
self.__cipher_aes = AES.new(self.__session_key, AES.MODE_EAX)
self.__nonce = self.__cipher_aes.nonce
def get_session_key(self):
return self.__cipher_rsa.encrypt(self.__session_key)
def get_nonce(self):
return self.__nonce
def encrypt(self, plaintext_bytes):
cipher_text, tag = self.__cipher_aes.encrypt_and_digest(plaintext_bytes)
return cipher_text, tag
@staticmethod
def decrypt(private_key, password, enc_session_key, nonce, tag, cipher_text):
plain_private_key = RSA.import_key(private_key, passphrase=password)
cipher_rsa = PKCS1_OAEP.new(plain_private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
return cipher_aes.decrypt_and_verify(cipher_text, tag)