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

# Load modules
import sys
from noop.ip.tcp import *
from hashlib import sha256
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]: host*
# argv[3]: port*
# argv[4]: password* (if RSA key file is password protected)
# *optional
host = "localhost"
port = 3456
passwd = None
if len(sys.argv) > 1:
    if len(sys.argv) > 4:
        passwd = sys.argv[4]
    frsakey = open(sys.argv[1], "rb")
    rsakey = RSA.importKey(frsakey.read(), passwd)
    frsakey.close()
else:
    sys.exit("Usage: %s privkey-file [host [port]]" % (sys.argv[0],))
if len(sys.argv) > 2:
    host = sys.argv[2]    
if len(sys.argv) > 3:
    port = int(sys.argv[3])

# A class to receive encrypted data
class SecComReceive:
    
    # Save address and password private key
    def __init__(self, address, privkey):
        self.addr = address
        self.privkey = privkey
        self.cipher = None

    # Receive cipher text and decrypt it
    def receive(self):
        if not self.cipher:
            tmp = self.privkey.decrypt(tcpreceive(self.addr))
            irv = tmp[:AES.block_size]
            aeskey = tmp[AES.block_size:]
            ctr = Counter.new(
                AES.block_size*8,
                initial_value=int.from_bytes(irv, 'little'))
            self.cipher = AES.new(aeskey, AES.MODE_CTR, counter=ctr)
        return self.cipher.decrypt(tcpreceive(self.addr))

# Create object to receive data from client, and then receive the data
scr = SecComReceive(IPaddr(node=host, port=port), rsakey)
print(scr.receive().decode())