import rsa import subprocess # First, initial client-server communication; key pair generation and exchange on the client side (pubkey, privkey) = rsa.newkeys(512) ########### server side INPUT_FILE = "/home/user/path/file" server_aes_key = rsa.randnum.read_random_bits(128) msg = "{i} asset encryption" err_vals = {} try: cmd = "openssl enc -aes-256-cbc -salt -in {i} -out {i}.enc -k {k}".format(i=INPUT_FILE, k=server_aes_key) subprocess.run(cmd, shell=True, check=True) except subprocess.CalledProcessError as e: msg += " error occurred.\nReturn code: {rc}\nStderr output of the process: {stderr}" err_vals = {"rc": e.returncode, "stderr": e.stderr if e.stderr is not None else ""} else: msg += " was successful" encrypted_aes_key = rsa.encrypt(server_aes_key, pubkey) finally: print(msg.format(i=INPUT_FILE, **err_vals)) # Then serve the encrypted_aes_key and AES-encrypted INPUT_FILE to the client ########### client side # Retrieve the encrypted_aes_key and AES-encrypted INPUT_FILE import rsa import subprocess client_aes_key = rsa.decrypt(encrypted_aes_key, privkey) # assert client_aes_key == server_aes_key msg = "{i} asset decryption" err_vals = {} try: cmd = "openssl enc -aes-256-cbc -d -salt -in {i}.enc -out {i}.dc -k {k}".format(i=INPUT_FILE, k=client_aes_key) subprocess.run(cmd, shell=True, check=True) except subprocess.CalledProcessError as e: msg += " error occurred.\nReturn code: {rc}\nStderr output of the process: {stderr}" err_vals = {"rc": e.returncode, "stderr": e.stderr if e.stderr is not None else ""} else: msg += " was successful" finally: print(msg.format(i=INPUT_FILE, **err_vals))