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

# Load modules
import sys, os
from noop.ip.tcp import *
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes

# Read arguments (host, port and password)
host = "localhost"
port = 3456
passwd = "pw"
if len(sys.argv) > 1:
    host = sys.argv[1]    
if len(sys.argv) > 2:
    port = int(sys.argv[2])
if len(sys.argv) > 3:
    passwd = sys.argv[3]

# A class to send encrypted data
class SecComSend:

    # Save address and password based key, and generate cipher    
    def __init__(self, address, pwd):
        self.addr = address
        dig = hashes.Hash(hashes.SHA256(), backend=default_backend())
        dig.update(pwd.encode())
        key = dig.finalize()
        self.irv = os.urandom(algorithms.AES.block_size//8)
        cip = Cipher(algorithms.AES(key), modes.CTR(self.irv), backend=default_backend())
        self.enc = cip.encryptor()
        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.irv)
        tcpsend(self.addr, (self.enc.update(msg) + self.enc.finalize()))

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