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.

Revisions

  1. stolarczyk revised this gist Sep 5, 2019. No changes.
  2. stolarczyk revised this gist Sep 5, 2019. No changes.
  3. stolarczyk revised this gist Sep 5, 2019. No changes.
  4. stolarczyk created this gist Sep 5, 2019.
    47 changes: 47 additions & 0 deletions large_file_rsa_encryption.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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))