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

from sys import argv, stdin, stdout
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto.Util import Counter

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

    # Password, if any
    passwd = None
    if len(argv) > 3:
        passwd = argv[3]

    # Read RSA key
    frsakey = open(argv[1], "rb")
    rsakey = RSA.importKey(frsakey.read(), passwd)
    frsakey.close()

    # Read and decrypt AES key
    faeskey = open(argv[2], "rb")
    aesinfo = rsakey.decrypt(faeskey.read())
    irv = aesinfo[:AES.block_size]
    aeskey = aesinfo[AES.block_size:]

    # Create AES cipher
    ctr = Counter.new(
        AES.block_size*8,
        initial_value=int.from_bytes(irv, "little"))
    cipher = AES.new(aeskey, AES.MODE_CTR, counter=ctr)

    # Read ciphertext from stdin and write plaintext to stdout
    while True:
        data = stdin.buffer.read()
        if not data: break
        stdout.buffer.write(cipher.decrypt(data))