class CustomCipher: def __init__(self): self.aes_cipher = AESCipher() self.rsa_cipher = RSACipher() def init_keys(self, secret_key, key_file): key = RSA.importKey(open(key_file, "rb")) public_key = key.publickey().exportKey('PEM') secret_key = hashlib.sha256(secret_key.encode()).digest() public_key = self.aes_cipher.encrypt(public_key, secret_key) return key, public_key, secret_key def gen_keys(self, secret_key, key_file): key = self.rsa_cipher.gen_key() public_key = key.publickey().exportKey('PEM') private_key = key.exportKey('PEM') secret_key = hashlib.sha256(secret_key.encode()).digest() public_key = self.aes_cipher.encrypt(public_key, secret_key) return key, public_key, secret_key def gen_key_file(self, file_name): with open(file_name + "-private.pem", "w") as priv_file: priv_file.write("{}".format(private_key)) with open(file_name + "-public.pem", "w") as pub_file: pub_file.write("{}".format(public_key)) def encrypt(self, public_key, secret_key, message): dec_public_key = self.aes_cipher.decrypt(public_key, secret_key) key = RSA.importKey(dec_public_key) result, encrypted = self.rsa_cipher.encrypt(key, message) return encrypted def decrypt(self, enc_message, key): result, decrypted = self.rsa_cipher.decrypt(key, enc_message) return decrypted def sign(self, key, data): return self.rsa_cipher.sign(key, data) def verify(self, public_key, secret_key, data, signature): dec_public_key = self.aes_cipher.decrypt(public_key, secret_key) key = RSA.importKey(dec_public_key) return self.rsa_cipher.verify(key, data, signature)
def main(): logger.debug("AUGPAKE_SERVER_IP: {}".format(AUGPAKE_SERVER_IP)) logger.debug("AUGPAKE_SERVER_PORT: {}".format(AUGPAKE_SERVER_PORT)) logger.debug("MQTT_BROKER_IP: {}".format(MQTT_BROKER_IP)) logger.debug("MQTT_BROKER_PORT: {}".format(MQTT_BROKER_PORT)) try: ID, Key = getKeyByAugPake(AUGPAKE_SERVER_IP, AUGPAKE_SERVER_PORT) except (OSError, IndexError) as e: logger.error(e) Key = None if Key is None: logger.error("Key is None. Exit...") exit() # create cipher cipher = AESCipher(Key) for line in tailf(WATCH_FILE): logger.debug("Plain Text: {}".format(line)) encrypt_ctx = cipher.encrypt(line) prefix_encrypt = ID + SEP + encrypt_ctx logger.debug("Encrypt Text prefixed ID: {}".format(prefix_encrypt)) publish.single(MQTT_TOPIC, prefix_encrypt, hostname=MQTT_BROKER_IP, port=MQTT_BROKER_PORT)
def __init__(self, serial_key, key_file): self.cipher = CustomCipher() key, public_key, secret_key = self.cipher.init_keys( serial_key, key_file) self.secret_key = secret_key self.public_key = public_key self.serial_key = serial_key self.key = key #print public_key #print secret_key # Ledger initialization aes_cipher = AESCipher() dev1_serial = "Device0001" dev1_serial_hash = hashlib.sha256(dev1_serial.encode()).digest() dev1_pub = aes_cipher.encrypt( RSA.importKey(open("device1-public.pem", "rb")).exportKey('PEM'), dev1_serial_hash) self.blockchain = Chain() self.blockchain.gen_next_block( hashlib.sha256("DeviceAccessBlock1".encode()).digest(), [{ "Serial": dev1_serial, "PubKey": dev1_pub }]) self.ledger = self.blockchain.output_ledger()
def test_enrcypted_data_is_decrypted_properly(): aes_cipher = AESCipher(key, IV) input_data = "some data" encrypted_data = aes_cipher.encrypt(input_data) decrypted_data = aes_cipher.decrypt(encrypted_data) assert input_data == decrypted_data
def process_network_message(self, data): aes_cipher = AESCipher() if self.is_paired: signature = self.sign(self.key, data) enc_data = aes_cipher.encrypt( data, hashlib.sha256(self.serial_key.encode()).digest()) message = json.dumps({ "message": enc_data, "signature": signature, "serial": self.serial_key }) enc_message = self.encrypt(self.network_serial_key, self.network_public_key, message) return enc_message return None
def process_access_message(self, serial): aes_cipher = AESCipher() if serial in self.ledger: data = json.dumps({ "type": "response", "serial": self.serial_key, "status": "approved" }) signature = self.sign(self.key, data) enc_data = aes_cipher.encrypt( data, hashlib.sha256(self.serial_key.encode()).digest()) message = json.dumps({ "message": enc_data, "signature": signature, "serial": self.serial_key }) enc_message = self.encrypt(serial, message) return enc_message return None
def main(): global AUGPAKE_SERVER_IP global AUGPAKE_SERVER_PORT global MQTT_BROKER_IP global MQTT_BROKER_PORT if os.environ.has_key("AUGPAKE_SERVER_IP"): AUGPAKE_SERVER_IP = os.environ.get("AUGPAKE_SERVER_IP") if os.environ.has_key("AUGPAKE_SERVER_PORT"): AUGPAKE_SERVER_PORT = os.environ.get("AUGPAKE_SERVER_PORT") if os.environ.has_key("MQTT_BROKER_IP"): MQTT_BROKER_IP = os.environ.get("MQTT_BROKER_IP") if os.environ.has_key("MQTT_BROKER_PORT"): MQTT_BROKER_PORT = os.environ.get("MQTT_BROKER_PORT") print("AUGPAKE_SERVER_IP:" + AUGPAKE_SERVER_IP) print("AUGPAKE_SERVER_PORT: " + AUGPAKE_SERVER_PORT) print("MQTT_BROKER_IP:" + MQTT_BROKER_IP) print("MQTT_BROKER_PORT: " + MQTT_BROKER_PORT) Key = getKeyByAugPake(AUGPAKE_SERVER_IP, AUGPAKE_SERVER_PORT) print("encrypt key is " + Key) cipher = AESCipher(Key) while True: j = random.randint(0, 2) encrypt_ctx = cipher.encrypt(sentance[j]) print ("Sending "+ encrypt_ctx + " : " + cipher.decrypt(encrypt_ctx)) publish.single("test", encrypt_ctx, hostname=MQTT_BROKER_IP, port=int(MQTT_BROKER_PORT)) time.sleep(j+1) # sleep random time
class Communicator(object): def __init__(self): self.aes_cipher = AESCipher() def send_enc_message(self, message, to_pickle, client_socket): """ :param message: message to send over the socket. :param to_pickle: a boolean which means whether to pickle the message to not. :param client_socket: the socket to send the message on. """ if to_pickle: message = f'{pickle.dumps(message)}{PICKLE_BIT}' if message.find(IMAGE_SUFFIX) != -1: encrypted_message = self.aes_cipher.encrypt_image_data( message[:-len(IMAGE_SUFFIX)]) else: encrypted_message = self.aes_cipher.encrypt(message) # message sending protocol: # first you send the length of the message # and then the message itself. try: client_socket.send( str(len(encrypted_message)).zfill(LEN_OF_LENGTH)) client_socket.send(encrypted_message) except socket.error: client_socket.close() except Exception as e: pass def get_dec_message(self, client_socket): """ :param client_socket: the client to receive the message from. :return: the client's message. """ message_length = self.get_message_length(client_socket) encrypted_message = self.get_message_by_length(message_length, client_socket) if encrypted_message.find(IMAGE_SUFFIX) is not -1: return self.aes_cipher.encrypt_image_data( encrypted_message[:-len(IMAGE_SUFFIX)]) decrypted_message = self.aes_cipher.decrypt(encrypted_message) if decrypted_message[-1:] == PICKLE_BIT: return pickle.loads(decrypted_message) return decrypted_message @staticmethod def get_message_length(client_socket): """ the function receives the length of the message. :return: the message length """ message_length = "" while len(message_length) != LEN_OF_LENGTH: message_length += client_socket.recv(LEN_OF_LENGTH - len(message_length)) return int(message_length) @staticmethod def get_message_by_length(message_length, client_socket): """ :param message_length: the length of the message. :param client_socket: the socket to listen on. :return: the message that was received. """ content = "" while len(content) != message_length: content += client_socket.recv(message_length - len(content)) return content
class UDPPackage(object): def __init__(self, pkg_type=constants.PKG_TYPE_HELLO, pkg_num=0, data=b'', password=None): self.pkg_type = pkg_type self.pkg_num = pkg_num self.data = data self.data_length = None self.data_hash = None self.data_length = self.__calculate_data_length__() self.data_hash = self.__calculate_data_hash__() self.password = password if self.password: self.cipher = AESCipher() def __calculate_data_length__(self): """ Calculate package data length """ return len(self.data) def __calculate_data_hash__(self): """ Calculate package data hash """ return mmh3.hash(self.data, signed=False) def __is_valid__(self): """ Checking is received data valid :return: """ logger.info("Checking is data valid") logger.debug("Data: {}".format(self.data)) calculated_hash = self.__calculate_data_hash__() logger.debug("Calculated data hash: {}".format(calculated_hash)) if calculated_hash != self.data_hash: logger.debug("Calculate hash {} does not equal to {}".format( calculated_hash, self.data_hash)) return False return True def __encrypt__(self): """ Encrypt package datae """ logger.info("Encrypt package data") key = self.cipher.gen_key(password=self.password) self.data = self.cipher.encrypt(key=key, data=self.data) def __decrypt__(self): """ Decrypt package data """ key = self.cipher.gen_key(password=self.password) self.data = self.cipher.decrypt(key=key, data=self.data) def pack(self) -> bytearray: """ Pack header and data to package :return: (byte array) Packed data to package """ if self.password: self.__encrypt__() self.data_length = self.__calculate_data_length__() self.data_hash = self.__calculate_data_hash__() logger.info("Packing data to package") logger.debug("Data length: {}".format(self.data_length)) logger.debug("Data hash: {}".format(self.data_hash)) pkg_header = struct.pack("IIII", self.pkg_type, self.pkg_num, self.data_length, self.data_hash) logger.debug("Package header: {}".format(pkg_header)) logger.debug("Package header length: {}".format(len(pkg_header))) logger.debug("Creating pkg bytearray") pkg = bytearray(pkg_header) pkg += self.data logger.debug("Data pkg: {}".format(pkg)) logger.debug("Data pkg len: {}".format(len(pkg))) return pkg def unpack(self): """ Unpack header and data from package :param data: Packed data package """ self.pkg_type, self.pkg_num, self.data_length, self.data_hash = struct.unpack( 'IIII', self.data[0:constants.TOTAL_HEADER_SIZE]) self.data = self.data[constants.TOTAL_HEADER_SIZE:] self.data_length = self.__calculate_data_length__() self.data_hash = self.__calculate_data_hash__() logger.debug("Is data valid: {}".format(self.__is_valid__())) if self.password: self.__decrypt__() def send(self, sock: struct, addr: str, port: int): """ Send data to socket :param sock: (struct) Socket :param addr: (string) Address :param port: (int) Port :return: Package object """ sock.sendto(self.pack(), (addr, port)) def receive(self, sock: struct, chunk_size: int = constants.CHUNK_SIZE) -> (struct, tuple): self.data, sender = sock.recvfrom(chunk_size + constants.TOTAL_HEADER_SIZE) logger.debug("Received: {}".format(self.data)) logger.debug("From: {}".format(sender)) self.unpack() return self, sender
import random import string from aes_cipher import AESCipher key_text = ''.join( [random.choice(string.ascii_letters + string.digits) for i in range(32)]) plain_text = 'test message.' cipher = AESCipher(key_text) encrypted = cipher.encrypt(plain_text) print(encrypted) decrypted = cipher.decrypt(encrypted) print(decrypted) print(decrypted == plain_text)