#-*- coding: utf-8 -*-
# (c) 2015 Anders Andersen
# See http://www.cs.uit.no/~aa/dist/tools/py/COPYING for details

import os
from sys import argv, stdin, stdout, stderr
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding

KEYSIZE = 256

# argv[1]: RSA key file name (reads)
# argv[2]: AES key file name (creates)
# stdin: input data
# stdout: output data
if len(argv) > 2:

    # Read public RSA key
    frsakey = open(argv[1], "rb")
    rsakey = serialization.load_pem_public_key(
        frsakey.read(),
        backend=default_backend())
    frsakey.close()

    # Generate, encrypt and save new AES key
    aeskey = os.urandom(KEYSIZE//8)
    irv = os.urandom(algorithms.AES.block_size//8)
    faeskey = open(argv[2], "wb")
    faeskey.write(rsakey.encrypt(
        irv + aeskey,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None)))
    faeskey.close()

    # Create AES cipher
    cipher = Cipher(algorithms.AES(aeskey), modes.CTR(irv), backend=default_backend())
    encryptor = cipher.encryptor()

    # Read plaintext from stdin and write ciphertext to stdout
    while True:
        data = stdin.buffer.read()
        if not data: break
        stdout.buffer.write(encryptor.update(data) + encryptor.finalize())