#-*- 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

# Define key size (AES key)
KEYSIZE = 256

# argv[1]: RSA key file name (reads)
# argv[2]: host*
# argv[3]: port*
# *optional
host = "localhost"
port = 3456
if len(sys.argv) > 1:
    frsakey = open(sys.argv[1], "rb")
    rsakey = RSA.importKey(frsakey.read())
    frsakey.close()
else:
    sys.exit("Usage: %s pubkey-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 send encrypted data
class SecComSend:

    # Save address and public key, and generate secret shared key
    def __init__(self, address, pubkey):
        self.addr = address
        self.pubkey = pubkey
        self.aeskey = Random.new().read(KEYSIZE//8)
        self.irv = Random.new().read(AES.block_size)
        ctr = Counter.new(
            AES.block_size*8,
            initial_value=int.from_bytes(self.irv, "little"))
        self.cipher = AES.new(self.aeskey, AES.MODE_CTR, counter=ctr)
        self._first_time = True

    # Encrypt message and send it
    def send(self, msg):
        if self._first_time:
            self._first_time = False
            tcpsend(self.addr,
                    self.pubkey.encrypt(self.irv + self.aeskey, b'')[0])
        tcpsend(self.addr, self.cipher.encrypt(msg))

# Create object to send encrypted data to server, and then send the data
scs = SecComSend(IPaddr(node=host, port=port), rsakey)
scs.send("hello".encode())
tcpflush()