#-*- 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.Cipher import AES
from Crypto.Util import Counter
# 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 receive encrypted data
class SecComReceive:
# Save address and password based key
def __init__(self, address, pwd):
self.addr = address
self.key = sha256(pwd.encode()).digest()
self._first_time = True
# Receive cipher text and decrypt it
def receive(self):
if self._first_time:
self._first_time = False
tmp = tcpreceive(self.addr)
while len(tmp) < AES.block_size:
tmp += tcpreceive(self.addr)
self.irv = tmp[:AES.block_size]
data = tmp[AES.block_size:]
ctr = Counter.new(
AES.block_size*8,
initial_value=int.from_bytes(self.irv, 'little'))
self.cipher = AES.new(self.key, AES.MODE_CTR, counter=ctr)
if not len(data) > 0:
data = tcpreceive(self.addr)
return self.cipher.decrypt(data)
# Create object to receive data from client, and then receive the data
scr = SecComReceive(IPaddr(node=host, port=port), passwd)
print(scr.receive().decode())