def test_encrypt_bytebuffer(self): crypter = Crypter(key=get_random_string(32), iv='The IV') initial_string = bytearray(random.getrandbits(8) for _ in range(1024)) encrypted = crypter.encrypt(initial_string) decrypted = crypter.decrypt(encrypted) self.assertTrue(len(decrypted) == len(initial_string)) self.assertTrue(decrypted == initial_string)
def test_encrypt_bytebuffer_notaligned_with_not_padded_key(self): crypter = Crypter(key=get_random_string(24), iv='The IV') initial_string = bytearray(random.getrandbits(8) for _ in range(723)) encrypted = crypter.encrypt(initial_string) decrypted = crypter.decrypt(encrypted) self.assertTrue(len(decrypted) == len(initial_string)) self.assertTrue(decrypted == initial_string)
def test_encrypt_bytestring(self): crypter = Crypter(key=get_random_string(24), iv='The IV') initial_string = b'Hello' encrypted = crypter.encrypt(initial_string) decrypted = crypter.decrypt(encrypted) self.assertTrue(len(decrypted) == len(initial_string)) self.assertTrue(bytes(decrypted, 'utf-8') == initial_string)
def test_crypter_ctor_with_invalid_parameters(self): with self.assertRaises(InvalidParameterException): Crypter(key=None, iv='ValidIV') with self.assertRaises(InvalidParameterException): Crypter(key=' ', iv='ValidIV') with self.assertRaises(InvalidParameterException): Crypter(key='ValidKey', iv=None) with self.assertRaises(InvalidParameterException): Crypter(key='ValidKey', iv=' ')
def test_message_exchange(self): crypto = Crypter('pwd', 'passphrase') sender = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', crypto) receiver = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', crypto) msg_to_send = get_random_string(1024) sender_th = Process(target=do_send, args=( sender, msg_to_send, )) # creating multiprocessing Queue results = multiprocessing.Queue() receiver_th = Process(target=do_recv, args=(receiver, results)) # Init threads sender_th.start() receiver_th.start() # Start threads sender_th.join() receiver_th.join() # Close Channels sender.close() receiver.close() self.assertTrue(results.qsize() == 1) received_msg = results.get() self.assertTrue(received_msg == msg_to_send)
def test_channel_ctor_missing_ifaceip(self): crypto = Crypter('pwd', 'passphrase') chan = Channel('224.1.1.1', 1234, 2048, None, crypto) self.assertTrue(chan.iface_ip == '0.0.0.0') chan.close()
def test_channel_set_read_blocking(self): reader_writer_mock = MagicMock() aton_mock = MagicMock(return_value=bytes()) inaddr_any_mock = MagicMock(return_value=123) mreq_mock = MagicMock() proto_ip_mock = MagicMock() ip_membership_mock = MagicMock() SOL_SOCKET_mock = MagicMock() SO_REUSEADDR_mock = MagicMock() self.mock_socket.socket.return_value = reader_writer_mock self.mock_socket.inet_aton.return_value = aton_mock self.mock_socket.INADDR_ANY = inaddr_any_mock self.mock_struct.pack = MagicMock(return_value=mreq_mock) self.mock_socket.IPPROTO_IP = proto_ip_mock self.mock_socket.IP_ADD_MEMBERSHIP = ip_membership_mock self.mock_socket.SOL_SOCKET = SOL_SOCKET_mock self.mock_socket.SO_REUSEADDR = SO_REUSEADDR_mock crypto = Crypter('pwd', 'passphrase') chan = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', crypto) # WHEN chan.set_read_blocking(False) # THEN chan.reader.setblocking.assert_called_with(0) # WHEN chan.set_read_blocking(True) # THEN chan.reader.setblocking.assert_called_with(1) chan.close()
def test_object_exchange(self): crypto = Crypter('pwd', 'passphrase') sender = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', crypto) receiver = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', crypto) msg_to_send = { 'number': get_random_string(1024), 'str': 'Hello world', 'bool': True } sender_th = Process(target=do_send_object, args=( sender, msg_to_send, )) # creating multiprocessing Queue results = multiprocessing.Queue() receiver_th = Process(target=do_recv_object, args=(receiver, results)) # Init threads sender_th.start() receiver_th.start() # Start threads sender_th.join() receiver_th.join() # Close Channels sender.close() receiver.close() self.assertTrue(results.qsize() >= 1) received_msg = results.get() self.assertTrue(received_msg == msg_to_send)
def test_serializable_object(self): crypter = Crypter(key=get_random_string(24), iv='The IV') import pickle import base64 # Encryption obj = SerializableObject(token='/patter/tester', payload={'key1': 'value1', 'key2': 123}) obj_b64 = base64.b64encode(pickle.dumps(obj)) encrypted_bytes = crypter.encrypt(obj_b64) # Decryption decrypted_bytes = crypter.decrypt(encrypted_bytes) decrypted_b64 = base64.b64decode(decrypted_bytes) decrypted_obj = pickle.loads(decrypted_b64) # Compare objects after encryption/serialization self.assertTrue(pickle.dumps(obj) == pickle.dumps(decrypted_obj))
def test_channel_reader_close_exception(self): crypto = Crypter('pwd', 'passphrase') chan = Channel('224.1.1.1', 1234, 2048, None, crypto) # HAVING chan.reader.close = MagicMock(side_effect=Exception()) # OBSERVE EXCEPTION with self.assertRaises(Exception): chan.close()
def test_channel_repr(self): crypto = Crypter('pwd', 'passphrase') chan = Channel('224.1.1.1', 1234, 2048, None, crypto) s = str(chan) self.assertTrue(s == 'MulticastCh<224.1.1.1:1234>') chan.close()
def main(): # name, mcastIP, mcastPort logger = logfactory.LogFactory('c1', 'logs/receiver') logger.info('Instantiating Receiver Sample') ch = Channel('224.1.1.1', 1234, crypto=Crypter('key', 'passphrase')) c = Component('c1', ch) ########################################## # REACTION ########################################## c.add('/arithm/calc/*', doStuff) c.start()
def test_channel_read_empty_data(self): crypto = Crypter('pwd', 'passphrase') chan = Channel('224.1.1.1', 1234, 2048, None, crypto) # HAVING chan.reader.recvfrom = MagicMock(return_value=(None, 'sender_addr')) # WHEN retval = chan.recv() # THEN self.assertIsNone(retval) chan.close()
def test_encrypt_and_decrypt_wrong_key(self): crypter = Crypter(key=' --- My Key --- ', iv='The IV') initial_string = ' Hello World ' encrypted = crypter.encrypt(initial_string) decrypter = Crypter(key=' --- No Key --- ', iv='The IV') self.assertFalse(decrypter.decrypt(encrypted) == initial_string)
def main(): # name, mcastIP, mcastPort logger = logfactory.LogFactory('sendr', 'logs/sender') logger.info('Instantiating Sender Sample') ch = channel.Channel('224.1.1.1', 1234, crypto=Crypter('key', 'passphrase')) c = Component('sendr', ch) # ACTIVE LOOP c.setLoop(loop) # REACTIONS c.add('/arithm/result', printResult) # START COMPONENT c.start()
def test_encrypt_long_key_and_decrypt(self): crypter = Crypter(key=get_random_string(32), iv='The IV') initial_string = get_random_string(1024) encrypted = crypter.encrypt(initial_string) self.assertTrue(crypter.decrypt(encrypted) == initial_string)
def test_encrypt_long_message_and_decrypt(self): crypter = Crypter(key=' --- My Key --- ', iv='The IV') initial_string = get_random_string(6000) encrypted = crypter.encrypt(initial_string) self.assertTrue(crypter.decrypt(encrypted) == initial_string)
def test_encrypt_and_decrypt_key_not_16bytes_should_pad_key(self): crypter = Crypter(key='SampleKey', iv='The IV') initial_string = ' Hello World ' encrypted = crypter.encrypt(initial_string) self.assertTrue(crypter.decrypt(encrypted) == initial_string)
def test_crypter_encrypt_with_invalid_parameter_type(self): with self.assertRaises(EncryptionInvalidParameterException): c = Crypter(key=get_random_string(32), iv='The IV') c.encrypt({'key': 'value'})
def test_encrypt_and_decrypt(self): crypter = Crypter(key=' --- My Key --- ', iv='The IV') initial_string = ' Hello World ' encrypted = crypter.encrypt(initial_string) self.assertTrue(crypter.decrypt(encrypted) == initial_string)
def test_crypter_decrypt_null_parameter(self): with self.assertRaises(InvalidParameterException): c = Crypter(key=get_random_string(32), iv='The IV') c.decrypt(None)
def test_crypter_ctor_with_too_long_key(self): with self.assertRaises(InvalidKeyLenghtException): Crypter(key=get_random_string(33), iv='The IV')
def test_channel_ctor(self): reader_writer_mock = MagicMock() aton_mock = MagicMock(return_value=bytes()) inaddr_any_mock = MagicMock(return_value=123) mreq_mock = MagicMock() proto_ip_mock = MagicMock() ip_membership_mock = MagicMock() SOL_SOCKET_mock = MagicMock() SO_REUSEADDR_mock = MagicMock() self.mock_socket.socket.return_value = reader_writer_mock self.mock_socket.inet_aton.return_value = aton_mock self.mock_socket.INADDR_ANY = inaddr_any_mock self.mock_struct.pack = MagicMock(return_value=mreq_mock) self.mock_socket.IPPROTO_IP = proto_ip_mock self.mock_socket.IP_ADD_MEMBERSHIP = ip_membership_mock self.mock_socket.SOL_SOCKET = SOL_SOCKET_mock self.mock_socket.SO_REUSEADDR = SO_REUSEADDR_mock crypto = Crypter('pwd', 'passphrase') ################# # WHEN - CTOR ################# chan = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', crypto) # THEN self.assertTrue(chan.mcast_ip == '224.1.1.1') self.assertTrue(chan.mcast_port == 1234) self.assertTrue(chan.bufsize == 2048) self.assertTrue(chan.iface_ip == '0.0.0.0') self.assertTrue(chan.crypto == crypto) chan.reader.setsockopt.assert_called() chan.reader.bind.assert_called_with((chan.iface_ip, chan.mcast_port)) chan.reader.setsockopt.assert_called_with(proto_ip_mock, ip_membership_mock, mreq_mock) chan.reader.setblocking.assert_called_with(1) chan.writer.setsockopt.assert_called() chan.writer.bind.assert_called_with((chan.iface_ip, chan.mcast_port)) chan.writer.setsockopt.assert_called_with(proto_ip_mock, ip_membership_mock, mreq_mock) self.mock_struct.pack.assert_called_with("4sI", aton_mock, inaddr_any_mock) ################# # WHEN - SEND ################# chan.send('Hello') # THEN chan.writer.sendto.assert_called_with(crypto.encrypt('Hello'), (chan.mcast_ip, chan.mcast_port)) ################# # WHEN - RECV ################# chan.reader.recvfrom = MagicMock( return_value=(crypto.encrypt('Response Data'), 'sender_addr')) (data, sender) = chan.recv() self.assertTrue(data == 'Response Data') self.assertTrue(sender == 'sender_addr') ################# # WHEN - CLOSE ################# chan.close() # THEN chan.writer.close.assert_called() chan.reader.close.assert_called()
#!/usr/bin/env python # Include parent folder in module resolution import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from multisock.channel import Channel from multisock.crypter import Crypter if __name__ == '__main__': udpchan = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', Crypter('pwd', 'passphrase')) print(f'Reading from {udpchan}') while True: (data, sender) = udpchan.recv() print(f'received from {sender}: [{data}] ')
import time import random from multisock.crypter import Crypter from multisock.channel import Channel from serializabledata import SerializableObject import logging root = logging.getLogger() root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) root.addHandler(handler) if __name__ == '__main__': udpchan = Channel('224.1.1.1', 1234, 2048, '0.0.0.0', Crypter('pwd', 'passphrase')) senderName = sys.argv[1] if len(sys.argv) > 1 else 'anonymous' for i in range(1000): obj = SerializableObject(token='/patter/tester', payload={'key1': 'value1', 'key2': i}) print(f'Sending to {udpchan}') udpchan.send_object(obj) time.sleep(random.randint(0, 1))