Skip to content

Instantly share code, notes, and snippets.

@stolarczyk
Last active September 5, 2019 19:17
Show Gist options
  • Save stolarczyk/5e7f3f64ad7c2d4e8db4221d29c1d23e to your computer and use it in GitHub Desktop.
Save stolarczyk/5e7f3f64ad7c2d4e8db4221d29c1d23e to your computer and use it in GitHub Desktop.
Sample implementation of client-server signing and verification of large files as described in the python rsa package documentation: https://stuvel.eu/python-rsa-doc/usage.html#how-it-usually-works
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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment