Ejemplo n.º 1
0
def main():
  print(sys.argv)
  CRT = True
  k = 6
  d = 256
  keygen = Keygen()
  decryptor = Decryptor()
  encryptor = Encryptor()
  file_processor = File_processor()
  keys = keygen.generate_keys(k,  d, CRT)
  file_processor.save_keys(keys, CRT)
  file_processor.read_keys(CRT)
  start_time = timer()
  encrypted = encryptor.encrypt(keys['public_n'], keys['public_e'], 'data/plain.txt', CRT)
  print("ENCRYPTION TIME MEASUE:")
  print(timer() - start_time) 
  start_time = timer()
  decrypted = decryptor.decrypt(keys, CRT, k, 'data/plain.txt.enc')
  print("DECRYPTION TIME MEASUE:")
  print(timer() - start_time) 
  print(decrypted)
  return 0
Ejemplo n.º 2
0
 def deserialize(cls,
                 username,
                 location: str = 'data/',
                 file_name: str = '_contacts_to_keys'):
     try:
         with open(location + username + file_name + '.txt', 'rb') as f:
             file_content = f.read()
             if file_content != b'':
                 res = json.loads(file_content)
                 for k, v in res.items():
                     cls.get_instance().contacts_to_keys[k] = {
                         'public_key':
                         Encryptor.load_public_key_from_string(
                             v['public_key']),
                         'symmetric_key':
                         v['symmetric_key']
                     }
     except FileNotFoundError:
         print('No such file')
Ejemplo n.º 3
0
class Server_Connector:

    encryptor = Encryptor()
    iocontroller = IO_controller()

    def __init__(self, IP_address, port):
        print('Creating socket')
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.IP_address = IP_address
        self.port = port

    def run(self):
        self.s.connect((self.IP_address, self.port))
        print('Succesfully connected to: ', self.IP_address)
        # Send a 1 to the server to let it know that you're a robot
        self.send('1')
        message = self.s.receive(1024)
        json_message = {'ready': True}
        self.send(json_message)
        while True:
            message = self.receive()
            if (message['type'] == 'route'):
                directions = message['routes']
                for directionlist in directions:
                    for direction in directionlist:
                        print('Next direction: ' + direction)
                        while (self.iocontroller.detect_node() == "line"):
                            pass
                        if (self.iocontroller.detect_node() == "node"):
                            # TODO draai naar dirction
                            print("Node detected")
                            #self.iocontroller.control_motors(directions)

    def send(self, message):
        jsonmessage = json.dumps(message)
        encryptedmessage = self.encryptor.encrypt(jsonmessage)
        self.s.send(encryptedmessage)

    def receive(self):
        receivedmessage = self.s.recv(1024)
        receivedmessage = self.encryptor.decrypt(receivedmessage)
        return json.loads(receivedmessage)
Ejemplo n.º 4
0
def register(username, password, email):
    public_key, private_key = Encryptor.generate_keys()
    Encryptor.save_private_key(private_key=private_key,
                               file_name=username + '_private_key')
    Encryptor.save_public_key(public_key=public_key,
                              file_name=username + '_public_key')
    content = {
        'username': username,
        'password': password,
        'public_key': Encryptor.get_public_key_as_string(public_key),
        'email': email
    }
    request = Request(action='register',
                      request_content=content,
                      request_sender=request_sender)
    request.send_request()
Ejemplo n.º 5
0
class Functionalities:
    additional = AdditionalFunctions()
    encryptor = Encryptor()

    def checkEfficiency(self):
        k = list()
        with open('./network/encryptor/network.json') as data_file:
            network = json.load(data_file)
        n = self.encryptor.getAsciiData()
        dataset = list()
        for i in n:
            i = list(i)
            i = list(map(int, i))
            i.append(0)
            dataset.append(i)

        for i in range(100):
            k.append(self.encryptor.predict(network, dataset[i], 0))
            k[i].append(dataset[i][:-1])

        c = list()
        for i in k:
            s = ""
            i = list(map(str, i))
            c.append(s.join(i))

        s = "Network is {}% efficient".format(len(list(dict.fromkeys(c))))
        return s

    def beginEncryption(self, file_path):
        with open('./network/encryptor/network.json') as data_file:
            network = json.load(data_file)
        data = list()
        f = open(file_path, "r")
        line = f.readline()
        while line != '':
            data.append(line)
            line = f.readline()
        bit_data = list()
        for i in data:
            bit_data.append(self.additional.text_to_bits(i))
        flag = 1
        for i in range(len(bit_data)):
            if ((len(bit_data[i])) % 8) != 0:
                print("data corrupted")
                flag = 0
                break
        if flag:
            input_data = list()
            for i in bit_data:
                l = len(i)
                k = int(l / 8)
                c = 0
                for j in range(k):
                    s = i[c:c + 8]
                    input_data.append(s)
                    c += 8

            c = 0
            for i in bit_data:
                l = len(i)
                c += int(l / 8)

            if c == len(input_data):
                print("data input is ready")

            bit_data = list()
            for i in input_data:
                a = list(i)
                b = list(i)
                a = list(map(int, a))
                b = list(map(int, b))
                a.append(b)
                bit_data.append(a)

            input_data = list()
            for i in bit_data:
                input_data.append(self.encryptor.predict(network, i, 0))

            bit_data = list()
            for i in input_data:
                s = ""
                i = list(map(str, i))
                bit_data.append(s.join(i))

            s = ""
            for i in bit_data:
                s += i

            code = base64.b64encode(zlib.compress(s.encode('utf-8'), 9))
            code = code.decode('utf-8')
            now = datetime.now()
            d1 = "./data/encrypted/" + now.strftime("%Y_%m_%d_%H%M%S") + ".txt"
            f = open(d1, 'w')
            f.write(code)
            f.close()

            s = "Encrypting the file \n{} \nis successfully completed".format(
                file_path.split("/")[-1])
            s += "\nEncrypted file stored at: \n{}".format(d1)

            return s

    def beginDecryption(self, file_path):
        with open('./network/decryptor/network_bit_2.json') as data_file:
            network2 = json.load(data_file)
        with open('./network/decryptor/network_bit_3.json') as data_file:
            network3 = json.load(data_file)
        with open('./network/decryptor/network_bit_4.json') as data_file:
            network4 = json.load(data_file)
        with open('./network/decryptor/network_bit_5.json') as data_file:
            network5 = json.load(data_file)
        with open('./network/decryptor/network_bit_6.json') as data_file:
            network6 = json.load(data_file)
        with open('./network/decryptor/network_bit_7.json') as data_file:
            network7 = json.load(data_file)
        with open('./network/decryptor/network_bit_8.json') as data_file:
            network8 = json.load(data_file)

        print("Enter path to encrypted file")
        file = open(file_path, 'r')
        text = file.read()
        file.close()

        decoded_txt = zlib.decompress(base64.b64decode(text))
        output = decoded_txt.decode()

        if len(output) % 8 != 0:
            print("corrupted data")
        else:
            c = 0
            l = len(output)
            k = int(l / 8)
            s = ""
            for i in range(k):
                word = list(output[c:c + 8])
                word = list(map(int, output[c:c + 8]))
                word.append(0)
                s += "0"
                s += self.encryptor.predict(network2, word, 2)
                s += self.encryptor.predict(network3, word, 3)
                s += self.encryptor.predict(network4, word, 2)
                s += self.encryptor.predict(network5, word, 2)
                s += self.encryptor.predict(network6, word, 2)
                s += self.encryptor.predict(network7, word, 2)
                s += self.encryptor.predict(network8, word, 2)
                c += 8

            c = 0
            l = len(output)
            k = int(l / 8)
            o = ""
            for i in range(k):
                u = self.additional.text_from_bits(s[c:c + 8])
                o += u
                c += 8

            now = datetime.now()
            d1 = "./data/decrypted/" + now.strftime("%Y_%m_%d_%H%M%S") + ".txt"
            f = open(d1, 'w')
            f.write(o)
            f.close()

            s = "Decrypting the file \n{} \nis successfully completed".format(
                file_path.split("/")[-1])
            s += "\nDecrypted file stored at \n{}".format(d1)

            return s
Ejemplo n.º 6
0
from encryptor import Encryptor

encryptor = Encryptor()
encrypted = ''

#string = input('Enter string to be encrypted: ')
string = encryptor.loadFile('text.txt')

chars = encryptor.getChars()
newChars = encryptor.encrypt(string)

for i in range(len(newChars)):
	print(newChars[i])

for i in range(len(newChars)):
	encrypted += newChars[i]


decrypted = encryptor.decrypt(encrypted)

for i in range(len(newChars)):
	print(decrypted[i])
Ejemplo n.º 7
0
 def test_wiring_type(self):
     with self.assertRaises(TypeError):
         Encryptor(wiring=42)
Ejemplo n.º 8
0
class DbNode():
    def _get_mixnode_list(self):
        def unhexlify_values(a_dict):
            for x in a_dict.keys():
                a_dict[x] = unhexlify(a_dict[x])
            return a_dict

        source = {
            'ip': self.broker_config['pkserver'],
            'port': self.broker_config['port']
        }
        mixnodes_dict = self.broker_comm.getMixNodeList({
            'ip': source['ip'],
            'port': source['port']
        })
        mixnodes_dict = unhexlify_values(mixnodes_dict)
        return mixnodes_dict

    def __init__(self, broker_config):
        self.private_key = None
        self.public_key = None
        self.ip = None
        self.params = getGlobalSphinxParams()
        self.network_sender = NetworkSender()
        self.broker_config = broker_config
        self.encryptor = Encryptor(self.params.group)
        self.mixnodes_list = None
        self.broker_comm = BrokerCommunicator()
        self.records = {}
        self.loadRecords()
        self.decoder = BinaryEncoderDecoder()

    def loadRecords(self):
        path = self.broker_config['database']
        f = open(path, 'r')
        self.records = json.load(f)

    def get_mixnode_list(self):
        if self.mixnodes_list is None:
            self.mixnodes_list = self._get_mixnode_list()
        return self.mixnodes_list

    def getIp(self):
        if self.ip is None:
            self.ip = getPublicIp()
        return self.ip

    def decrypt(self, iv, text, pk, tag):
        msg = self.encryptor.decrypt_aes_gcm((pk, iv, text, tag),
                                             self.private_key[1])
        return msg

    def encrypt(self, msg, client_key):
        g_x, iv, ciphertext, tag = self.encryptor.encrypt_aes_gcm(
            msg, client_key, os.urandom(16))
        encrypted_reply = {'pk': g_x, 'iv': iv, 'text': ciphertext, 'tag': tag}
        return encrypted_reply

    def xor_records(self, mlist):
        records = self.getRecords()
        for row in mlist:
            message = ''
            for i in range(0, len(row)):
                if row[i] == 1:
                    if message == '':
                        message = records[i]
                    else:
                        message = pir_executor.stringXorer(message, records[i])
        return message

    def getRecords(self):
        return self.records

    def getRecordsSize(self):
        length = len(self.records['collection'])
        print(length)
        return length

    def fetch_answer(self, msg):
        print("here")
        try:
            db_cache = self.getRecords()['collection']
            pir_xor = msg['pir_xor']
            if not pir_xor:
                index = msg['index']
                return db_cache[index]
            else:
                pir_executor = PIRExecutor()
                vector = msg['index']
                print("Decoding")
                vector = self.decoder.decode_binary(vector, len(db_cache))
                print("Decoded")
                message = ''
                for i, val in enumerate(vector):
                    if val == 1:
                        if message == '':
                            message = db_cache[i]
                        else:
                            message = pir_executor.stringXorer(
                                message, db_cache[i])
                return message
        except IndexError:
            return b'No such index in the database.'

    def publish_key(self):
        def prepare_sending_pk(public_key, server_config):
            key_server_ip = server_config['pkserver']
            port = server_config['port']
            try:
                response = os.system("ping -c 1 " + key_server_ip)
                if response != 0:
                    raise ValueError(
                        "Server: {} cannot be reached. The key was not published"
                        .format(ip))
                else:
                    request_creator = RequestCreator()
                    json_data, destination = request_creator.post_db_key_request(
                        {
                            'ip': key_server_ip,
                            'port': port
                        }, {
                            'id': public_key[0],
                            'pk': public_key[2]
                        })
                    return (json_data, destination)
            except Exception as error:
                print("Unexpected error: {}".format(error))
                return None
            return None

        self.public_key, self.private_key = self.encryptor.keyGenerate(
            self.getIp())
        json_data, destination = prepare_sending_pk(self.public_key,
                                                    self.broker_config)
        #publish key
        response = self.network_sender.send_data(json_data, destination)
        return response
Ejemplo n.º 9
0
if encryption_mode == 'cfb':
    decrypted_key2 = Decrypter.simulate_aes_cbc_decryption([encrypted_key2],
                                                           secret_key3, iv_k3)
    decrypted_iv_k2 = Decrypter.simulate_aes_cbc_decryption([encrypted_iv_k2],
                                                            secret_key3, iv_k3)
else:
    decrypted_key2 = Decrypter.simulate_aes_cfb_decryption([encrypted_key2],
                                                           secret_key3, iv_k3)
    decrypted_iv_k2 = Decrypter.simulate_aes_cfb_decryption([encrypted_iv_k2],
                                                            secret_key3, iv_k3)

decrypted_iv_k2 = bytes(decrypted_iv_k2.encode('utf8'))

# sending the encrypted key back for confirmation
if encryption_mode == 'cfb':
    encrypted_key_to_confirm = Encryptor.simulate_aes_cbc_encryption(
        decrypted_key2, secret_key3, iv_k3)[0]
else:
    encrypted_key_to_confirm = Encryptor.simulate_aes_cfb_encryption(
        decrypted_key2, secret_key3, iv_k3)[0]

confirmation_message = pickle.dumps(encrypted_key_to_confirm)
soc.sendall(confirmation_message)

message = soc.recv(128).decode('utf8')
print(message)

print('[CLIENT B] Receiving data... ')
message = soc.recv(20480000)

decoded_message = pickle.loads(message)
if encryption_mode == 'cfb':
 def __init__(self):
     self._data = Encryptor.getData(Encryptor())
Ejemplo n.º 11
0
class Gui:
    flag = 1
    window = Tk()
    window.geometry("430x450")
    window.resizable(0, 0)
    window.title("Installation Wizard")
    e = Encryptor()

    #    def btn_click(self, item):
    #        global expression
    #        expression = expression + str(item)
    #        input_text.set(expression)
    #
    #    def btn_clear(self):
    #        global expression
    #        expression = ""
    #        input_text.set("")
    #
    #    def btn_equal(self):
    #        global expression
    #        result = str(eval(expression))
    #        input_text.set(result)
    #        expression = ""

    def execute(self, flag):
        if path.exists("./network/encryptor/network.json"):
            self.labelText.set(
                "Application is already installed in your system\nClose this window and launch the application"
            )
        else:
            global expression
            expression = ""
            self.labelText.set(
                "Installing the encryptor\nSee terminal for details")
            self.e.main()
            self.labelText.set("Installation Finished")
            self.flag = 0

    def destroy_session(self, window):
        window.destroy()

    expression = ""

    input_text = StringVar()
    labelText = StringVar()

    input_frame = Frame(window,
                        width=312,
                        height=50,
                        bd=0,
                        highlightbackground="black",
                        highlightcolor="black",
                        highlightthickness=1)

    input_frame.pack(side=TOP)

    input_field = Entry(input_frame,
                        font=('arial', 18, 'bold'),
                        textvariable=input_text,
                        width=50,
                        bg="#eee",
                        bd=0,
                        justify=RIGHT)

    input_field.grid(row=0, column=0)

    input_field.pack(ipady=10)

    btns_frame = Frame(window, width=312, height=272.5)

    btns_frame.pack(side=TOP)

    btns_frame2 = Frame(window, width=312, height=72.5, bg="grey")

    btns_frame2.pack(side=BOTTOM)

    label = Label(btns_frame,
                  text="Neural Encryptor",
                  fg="Red",
                  width=55,
                  height=3,
                  bd=0,
                  bg="#cfa").grid(
                      row=0,
                      column=0,
                      columnspan=2,
                  )

    install = Button(btns_frame,
                     text="Install",
                     fg="black",
                     font=('Times new roman', 12, 'bold'),
                     width=24,
                     height=3,
                     bd=2,
                     bg="#fff",
                     cursor="hand2",
                     command=lambda: Gui().execute(Gui().flag)).grid(
                         row=1,
                         column=0,
                     )

    destroy = Button(btns_frame,
                     text="Exit",
                     fg="black",
                     font=('Times new roman', 12, 'bold'),
                     width=24,
                     height=3,
                     bd=2,
                     bg="#fff",
                     cursor="hand2",
                     command=lambda: Gui().destroy_session(Gui().window)).grid(
                         row=1,
                         column=1,
                     )

    message = Label(
        btns_frame,
        textvariable=labelText,
        fg="Black",
        font=('Times new roman', 12, 'bold'),
        width=55,
        height=12,
        bd=0,
    ).grid(
        row=2,
        column=0,
        columnspan=2,
        pady=5,
    )

    s = "Developed by : Saketh G"

    label2 = Label(btns_frame2,
                   text=s,
                   fg="Black",
                   width=55,
                   height=1,
                   bd=0,
                   bg="#cfa").grid(row=3, column=0, columnspan=2)
Ejemplo n.º 12
0
    def test_wiring_length(self):
        with self.assertRaises(ValueError):
            Encryptor(wiring='ABC')

        with self.assertRaises(ValueError):
            Encryptor(wiring='ABCDEFGHIJKLMNOPQRSTUVWXYZa')
Ejemplo n.º 13
0
 def setUp(self):
     super(EncrytorTest, self).setUp()
     self.encryptor = Encryptor(secrets.password)
     self.encryptor.cipher_storage.create_cipher()
Ejemplo n.º 14
0
class EncrytorTest(unittest.TestCase):
    def setUp(self):
        super(EncrytorTest, self).setUp()
        self.encryptor = Encryptor(secrets.password)
        self.encryptor.cipher_storage.create_cipher()

    def test_string_encryption(self):
        data = "hello"
        encrypted = self.encryptor.encrypt(data, string=True)
        decrypted = self.encryptor.decrypt(encrypted, string=True)

        self.assertEqual(data, decrypted)

    def test_file_name_encryption(self):
        data = "hello"
        encrypted = self.encryptor.encrypt(data, file_name=True)
        decrypted = self.encryptor.decrypt(encrypted, file_name=True)

        self.assertEqual(data, decrypted)

    def test_file_encryption_in_place(self):
        file_name = "test_file"
        data = "test data here..."
        if os.path.exists(file_name):
            self.fail("File with name {} exists.".format(file_name))

        file_ptr = open(file_name, mode="w+")
        file_ptr.write(data)
        file_ptr.flush()

        passed = False
        try:
            self.encryptor.encrypt(file_name, is_file=True)
            # file_ptr.seek(0)
            # encrypted = file_ptr.read()
            # self.assertFalse(encrypted == data)
            self.encryptor.decrypt(file_name, is_file=True)
            file_ptr.seek(0)
            decrypted = file_ptr.read()
            self.assertEqual(data, decrypted, "Decrypted text does not equal the original text.")
            passed = True
        finally:
            os.remove(file_name)
            self.assertTrue(passed)

    def test_file_encryption_encryption_different_file(self):
        file_in = "test_file.in"
        file_out = "test_file.out"
        data = "test data here..."

        if os.path.exists(file_in) or os.path.exists(file_out):
            self.fail("File with name {} or {} exists.".format(file_in, file_out))

        file_ptr = open(file_in, mode="w+")
        file_ptr.write(data)
        file_ptr.flush()

        passed = False

        try:
            self.encryptor.encrypt(file_in, is_file=True, target_path=file_out)
            # file_ptr.seek(0)
            # encrypted = file_ptr.read()
            # self.assertFalse(encrypted == data)
            self.encryptor.decrypt(file_out, is_file=True)
            file_ptr = open(file_out)
            decrypted = file_ptr.read()
            self.assertEqual(data, decrypted, "Decrypted text does not equal the original text.")
            passed = True
        finally:
            os.remove(file_in)
            os.remove(file_out)
            self.assertTrue(passed, "Tests did not pass.")

    def test_encryption_decryption_in_different_file(self):
        file_in = "ttest_file.in"
        file_out = "test_file.out"
        data = "test data here..."

        if os.path.exists(file_in) or os.path.exists(file_out):
            self.fail("File with name {} or {} exists.".format(file_in, file_out))

        file_ptr = open(file_in, mode="w+")
        file_ptr.write(data)
        file_ptr.flush()

        passed = False

        try:
            self.encryptor.encrypt(file_in, is_file=True)
            # file_ptr.seek(0)
            # encrypted = file_ptr.read()
            # self.assertFalse(encrypted == data)
            self.encryptor.decrypt(file_in, is_file=True, target_path=file_out)
            file_ptr = open(file_out)
            decrypted = file_ptr.read()
            self.assertEqual(data, decrypted, "Decrypted text does not equal the original text.")
            passed = True
        finally:
            os.remove(file_in)
            os.remove(file_out)
            self.assertTrue(passed, "Tests did not pass.")
    def __init__(self):
        self._data = Encryptor.getData(Encryptor())
	self._mailServer = 'smtp.gmail.com'
	self._mailServerPort = 587
Ejemplo n.º 16
0
from encryptor import Encryptor
from decryptor import Decryptor
publicCertificate = "/Users/mcastro/Desktop/public.pem"
privateCertificate = "/Users/mcastro/Desktop/private.pem"
jsonFile = "/Users/mcastro/Desktop/encrypt.json"

keysize = 32  #32 bytes
blockSize = 128  #128 bits
ivSize = 16  #16 bytes

inputString = input("Input message to encrypt: ")
print("Encrypting message: ", inputString)
myEncryptor = Encryptor(keysize, blockSize, ivSize, inputString,
                        publicCertificate, jsonFile)
myEncryptor.encrypt()
print("Message encrypted")

print("\nMessasge will now be decrypted")
myDecryptor = Decryptor(keysize, blockSize, ivSize, jsonFile,
                        privateCertificate)
myDecryptor.decrypt()
Ejemplo n.º 17
0
    def process_response(self) -> str:
        if self.response_status == 1:
            print('ERR')
            return ''
        elif self.response_status == 2:
            print('LOGIN_NOT_AVAILABLE')
            return ''
        elif self.response_status == 3:
            print('INVALID_ACTION')
            return ''
        elif self.response_status == 4:
            print('WRONG_PASSWORD')
            return ''
        elif self.response_status == 5:
            print('USER_DO_NOT_EXIST')
            return ''
        elif self.response_status == 6:
            print('AUTHENTICATION_REQUIRED')
        elif self.response_status == 7:
            print('CONNECT_ALREADY_PENDING')
            return ''

        if self.action not in ['authenticate', 'register']:
            key = client_session.ClientSession.get_server_symmetric_key()
            self.content = Encryptor.symmetrical_decrypt(key=key,
                                                         message=self.content)
            self.content = json.loads(self.content)

        print(self.action, ' response content: ', type(self.content),
              self.content)

        result = ''
        if self.action == 'message':
            pass
        elif self.action == 'authenticate':
            client_session.ClientSession.set_server_symmetric_key(
                self.content['key'])
        elif self.action == 'search':

            ContactsToKeys.add_contact_public_key(
                username=self.content['username'],
                public_key=self.content['key'])
        # expects {response_content: {message_array: [{content: str, sender: str, recipient: str}]}}
        elif self.action == 'getallmsgs':
            pass
        # expects {response_content: {message_array: [{content: str, sender: str, recipient: str}]}}
        elif self.action == 'getnewmsgs':
            accept_contact = True

            # content = json.loads(self.content)
            for msg in self.content['message_array']:
                sender = msg['sender']
                recipient = msg['recipient']
                content = msg['content']

                # new message from a contact
                if Contacts.contact_exists(sender) and Contacts.get_contact(
                        sender).is_connected():
                    Contacts.get_contact(sender).add_message(
                        UserMessage(sender=sender,
                                    recipient=recipient,
                                    content=content))
                    print(msg)
                # response to a connect request
                elif Contacts.contact_exists(
                        sender
                ) and not Contacts.get_contact(sender).is_connected():
                    sender = Contacts.get_contact(sender)
                    sender.is_connected()
                    private_key = client_session.ClientSession.get_client_private_key(
                    )
                    decrypted_key = Encryptor.asymmetric_decrypt_message(
                        key=private_key, message=content['key'])
                    ContactsToKeys.add_contact_symmetric_key(
                        symmetric_key=decrypted_key,
                        username=sender.get_username())
                    ContactsToKeys.add_contact_public_key(
                        public_key=content['public_key'],
                        username=sender.get_username())
                # accepting incoming connect request
                elif accept_contact:
                    Contacts.add_contact(Contact(sender, connected=True))
                    sender = Contacts.get_contact(sender)
                    private_key = client_session.ClientSession.get_client_private_key(
                    )
                    content = json.loads(content)
                    decrypted_key = Encryptor.asymmetric_decrypt_message(
                        key=private_key, message=content['key'])
                    ContactsToKeys.add_contact_symmetric_key(
                        symmetric_key=decrypted_key,
                        username=sender.get_username())
                    ContactsToKeys.add_contact_public_key(
                        public_key=content['public_key'],
                        username=sender.get_username())
                    content = {}
                    content['key'] = ContactsToKeys.get_contact_symmetric_key(
                        sender.get_username())
                    content['pubic_key'] = Encryptor.\
                        get_public_key_as_string(client_session.ClientSession.get_client_public_key())
                    content = json.dumps(content)

                    req = request.Request(action='connect',
                                          request_content=UserMessage(
                                              recipient=sender,
                                              sender=recipient,
                                              content=content).as_dict(),
                                          request_sender=sender)
                    req.send_request()
                # rejecting incoming connect request
                else:
                    req = request.Request(action='block',
                                          request_content={'username': sender},
                                          request_sender=sender)
                    req.send_request()

        elif self.action == 'register':
            pass
        elif self.action == 'delete_account':
            Contacts.delete_all_contacts()
            ContactsToKeys.delete_all_records()

        return result
Ejemplo n.º 18
0
def fTestEnc():
    print("fTestEnc")
    e = Encryptor()

    # Check fGenDict
    d = e.fGenDict()
    # check if every char in dict
    success = True
    for c in Encryptor.chars:
        if not c in d and success:
            print("fGenDict FAILED!")
            success = False
    if success:
        print("fGenDict Success!")

    # Check fReverseDict
    success = True
    rd = e.fReverseDict(d)
    for k, v in rd.items():
        if not d[v] == k and success:
            print("fReverseDict FAILED!")
    if success:
        print("fReverseDict Success!")

    # check key encryption
    msg = "quick brown fox jumped over fence!><P@*ASND *!@ DHA"

    # fGenKeys, nothing to check
    # keys = e.fGenKeys(len(msg)//2, len(msg)//6 + 1)
    keys = [1, 2, 3]

    # fEncryptKeys and fDecryptKeys
    mk = e.fEncryptKeys(msg, e.default, keys)
    if mk == msg:
        print("fEncryptKeys FAILED!")
    else:
        print("fEncryptKeys Success!")

    mk = e.fDecryptKeys(mk, e.default, keys)
    if mk != msg:
        print("fDecryptKeys FAILED!")
        print(mk, msg)
    else:
        print("fDecryptKeys Success!")

    # fEncryptDict and with reversed dict
    success = True
    mk = e.fEncryptDict(msg, d)
    if mk == msg:
        print("fEncryptDict FAILED!")
    else:
        print("fEncryptDict Success!")

    mk = e.fEncryptDict(mk, rd)
    if mk != msg:
        print("fEncryptDict in reverse FAILED!")
        print(msg, mk)
    else:
        print("fEncryptDict in reverse Success!")

    # fGenFuncs
    fEnc, fDec = e.fGenFuncs(20)
    mk = fEnc(msg)
    if mk == msg:
        print("fGenFuncs fEnc FAILED!")
    else:
        print("fGenFuncs fEnc Success!")

    mk = fDec(mk)
    if msg != mk:
        print("fGenFuncs fDec FAILED")
    else:
        print("fGenFuncs fDec Success!")
Ejemplo n.º 19
0
encrypted_iv_k1 = encrypted_data[2]

if encryption_mode == 'cbc':
    decrypted_key1 = Decrypter.simulate_aes_cbc_decryption([encrypted_key],
                                                           secret_key3, iv_k3)
    decrypted_iv_k1 = Decrypter.simulate_aes_cbc_decryption([encrypted_iv_k1],
                                                            secret_key3, iv_k3)
else:
    decrypted_key1 = Decrypter.simulate_aes_cfb_decryption([encrypted_key],
                                                           secret_key3, iv_k3)
    decrypted_iv_k1 = Decrypter.simulate_aes_cfb_decryption([encrypted_iv_k1],
                                                            secret_key3, iv_k3)

# sending the encrypted key back for confirmation
if encryption_mode == 'cbc':
    encrypted_key_to_confirm = Encryptor.simulate_aes_cbc_encryption(
        decrypted_key1, secret_key3, iv_k3)[0]
else:
    encrypted_key_to_confirm = Encryptor.simulate_aes_cfb_encryption(
        decrypted_key1, secret_key3, iv_k3)[0]

confirmation_message = pickle.dumps(encrypted_key_to_confirm)
soc.sendall(confirmation_message)

message = soc.recv(128).decode('utf8')
print(message)

# encrypting and sending the file in blocks
file_name = input('[Client A] Enter file name you want to encrypt and send: ')
while not path.exists(file_name):
    print(f'[Client A] The file {file_name} does not exists. Try again...')
    file_name = input(
Ejemplo n.º 20
0
if __name__ == "__main__":
  if sys.argv[1] == 'test':
    main()
  elif sys.argv[1] == 'gen':
    k, d = int(sys.argv[2]), int(sys.argv[3])
    CRT = True if int(sys.argv[4]) == 1 else False
    keygen = Keygen()
    file_processor = File_processor()
    start_time = timer()
    keys = keygen.generate_keys(k,  d, CRT)
    file_processor.save_keys(keys, CRT)
  elif sys.argv[1] == 'enc':
    CRT = True if int(sys.argv[2]) == 1 else False
    file_processor = File_processor()
    keys = file_processor.read_keys(CRT)
    encryptor = Encryptor()
    start_time = timer()
    encrypted = encryptor.encrypt(keys['public_n'], keys['public_e'], 'data/plain.txt', CRT)
    print("ENCRYPTION TIME MEASUE:")
    print(timer() - start_time) 
  elif sys.argv[1] == 'dec':
    k = int(sys.argv[2])
    CRT = True if int(sys.argv[3]) == 1 else False
    file_processor = File_processor()
    keys = file_processor.read_keys(CRT)
    decryptor = Decryptor()
    start_time = timer()
    decrypted = decryptor.decrypt(keys, CRT, k, 'data/plain.txt.enc')
    print("DECRYPTION TIME MEASUE:")
    print(timer() - start_time) 
    print(decrypted)
Ejemplo n.º 21
0
class Application:
    flag = 1
    window = Tk()
    window.geometry("445x470")
    #window.resizable(0, 0)
    window.title("Neural Encryptor")
    e = Encryptor()
    func = Functionalities()

    def encrypt_function(self):
        if path.exists("./network/encryptor/network.json"):
            self.filename = askopenfilename(
                initialdir="/home/cp/Documents/Hackathon",
                title="Select A File")
            s = self.func.beginEncryption(self.filename)
            self.labelText.set(s)
        else:
            s = "Encryptor is not installed in your system"
            s += "\nPlease Install the Encryptor"
            self.labelText.set(s)

    def decrypt_function(self):
        if path.exists("./network/encryptor/network.json"):
            self.filename = askopenfilename(initialdir="./data/encrypted",
                                            title="Select A File")
            s = self.func.beginDecryption(self.filename)
            self.labelText.set(s)
        else:
            s = "Encryptor is not installed in your system"
            s += "\nPlease Install the Encryptor"
            self.labelText.set(s)

    def check_efficiency(self):
        if path.exists("./network/encryptor/network.json"):
            s = self.func.checkEfficiency()
            self.labelText.set(s)
        else:
            s = "Encryptor is not installed in your system"
            s += "\nPlease Install the Encryptor"
            self.labelText.set(s)

    def destroy_session(self, window):
        window.destroy()

    expression = ""

    input_text = StringVar()
    labelText = StringVar()

    btns_frame = Frame(window, width=55, height=272.5)

    btns_frame.pack(side=TOP)

    btns_frame2 = Frame(window, width=55, height=72.5, bg="grey")

    btns_frame2.pack(side=BOTTOM)

    label = Label(btns_frame,
                  text="Welcome to Neural Encryptor",
                  fg="Red",
                  width=55,
                  height=3,
                  bd=0,
                  bg="#cfa").grid(
                      row=0,
                      column=0,
                  )

    encrypt = Button(btns_frame,
                     text="Encrypt a file",
                     fg="black",
                     font=('Times new roman', 12, 'bold'),
                     width=50,
                     height=3,
                     bd=2,
                     bg="#fff",
                     cursor="hand2",
                     command=lambda: Application().encrypt_function()).grid(
                         row=1,
                         column=0,
                     )

    decrypt = Button(btns_frame,
                     text="Decrypt a file",
                     fg="black",
                     font=('Times new roman', 12, 'bold'),
                     width=50,
                     height=3,
                     bd=2,
                     bg="#fff",
                     cursor="hand2",
                     command=lambda: Application().decrypt_function()).grid(
                         row=2,
                         column=0,
                     )

    efficiency = Button(btns_frame,
                        text="Check Efficiency of the encryptor",
                        fg="black",
                        font=('Times new roman', 12, 'bold'),
                        width=50,
                        height=3,
                        bd=2,
                        bg="#fff",
                        cursor="hand2",
                        command=lambda: Application().check_efficiency()).grid(
                            row=3,
                            column=0,
                        )

    destroy = Button(btns_frame,
                     text="Exit",
                     fg="black",
                     font=('Times new roman', 12, 'bold'),
                     width=50,
                     height=3,
                     bd=2,
                     bg="#fff",
                     cursor="hand2",
                     command=lambda: Application().destroy_session(Application(
                     ).window)).grid(
                         row=4,
                         column=0,
                     )

    message = Label(
        btns_frame,
        textvariable=labelText,
        fg="Black",
        font=('Times new roman', 12, 'bold'),
        width=55,
        height=4,
        highlightbackground="black",
        highlightcolor="black",
        highlightthickness=1,
        bd=0,
    ).grid(
        row=5,
        column=0,
        columnspan=2,
        ipady=11,
    )

    s = "Developed by : Saketh G"

    label2 = Label(btns_frame2,
                   text=s,
                   fg="Black",
                   width=55,
                   height=1,
                   bd=0,
                   bg="#cfa").grid(row=6, column=0, columnspan=2)
Ejemplo n.º 22
0
 def test_constructor(self):
     self.assertTrue(isinstance(Encryptor(), Encryptor))
     self.assertTrue(
         isinstance(Encryptor(wiring='ZAQXSWCDEVFRBGTNHYMJUKILOP'),
                    Encryptor))
     self.assertTrue(isinstance(Encryptor(initial_position=25), Encryptor))
Ejemplo n.º 23
0
class Client:
    def __init__(self, public_key_server):
        self.broker_comm = BrokerCommunicator()
        self.public_key_server = public_key_server
        self.db_list = None
        self.mixnode_list = None
        self.ip = getPublicIp()
        self.encryptor = Encryptor(getGlobalSphinxParams().group)
        self.surbDict = {}

    def encryptForDB(self, msg, key, session_name):
        getGlobalSphinxParams().group
        g_x, iv, ciphertext, tag = self.encryptor.encrypt_aes_gcm(
            msg, key, session_name)
        e_message = {
            'pk': g_x.export(),
            'iv': iv,
            'text': ciphertext,
            'tag': tag
        }
        json_msg = dumps(e_message)
        return (json_msg)

    def getDBRecordSize(self, portEnum, network_sender):
        session_name = os.urandom(16)
        self.public_key, self.private_key = self.encryptor.keyGenerate(
            session_name)
        db_dest, key = self.create_db_destination(0, portEnum.db.value)
        message = encode(
            self.create_db_message(
                None, {
                    'pir_xor': None,
                    'request_type': RequestType.get_db_size.value,
                    'pk': self.public_key
                }))
        json_msg = self.encryptForDB(message, key, session_name)
        response = network_sender.send_data_wait(json_msg, {
            'ip': db_dest[0],
            'port': db_dest[2]
        })
        response = int(decode(response))
        return response

    def xor(self, messages):
        pir_executor = PIRExecutor()
        message = messages[0]
        for m in messages[1:]:
            message = pir_executor.stringXorer(message, m)
        if len(messages) > 1:
            return message.decode().strip()
        else:
            return message.strip()

    def decrypt(self, cipher, private_key):
        iv = cipher['iv']
        text = cipher['text']
        pk = cipher['pk']
        tag = cipher['tag']
        msg = self.encryptor.decrypt_aes_gcm((pk, iv, text, tag), private_key)
        return msg

    def poll_recordSize(self, DummyIndex):
        self.client_poller = ClientPoller()
        messages = {}
        threads = []
        for surbid, data in self.surbDict.items():
            threads.append(
                self.client_poller.poll_with((surbid, data['source']), self,
                                             messages))
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        # First one is the record size
        surbid = list(self.surbDict.keys())[0]
        self.surbDict = {}
        record_size = decode(
            self.decrypt(messages[surbid][1], self.private_key[1]))
        return record_size

    def poll_index(self, pir, requested_index):
        self.client_poller = ClientPoller()
        threads = []
        messages = {}
        for surbid, data in self.surbDict.items():
            threads.append(
                self.client_poller.poll_with((surbid, data['source']), self,
                                             messages))
        for t in threads:
            t.start()
        for t in threads:
            t.join()

        decrypted_msgs = []
        if not pir:
            decrypted_msgs = {}
        try:
            for surbid, _ in self.surbDict.items():
                msg = self.surbDict[surbid]
                log_debug(msg)
                decrypted_msg = decode(
                    self.decrypt(messages[surbid][1], msg['key'][1]))
                if pir:
                    decrypted_msgs.append(decrypted_msg)
                else:
                    decrypted_msgs[messages[surbid][0]] = decrypted_msg
            if pir:
                return self.xor(decrypted_msgs)
            else:
                return decrypted_msgs[requested_index].strip()
        except Exception as e:
            PrintException()
            log_debug('[ERROR] Exception\n{}\n'.format(e))

    def recoverMessage(self, msg, myid):
        surbkeytuple = self.surbDict[myid]['surbkeytuple']
        index = self.surbDict[myid]['index']
        return (index,
                decode(receive_surb(getGlobalSphinxParams(), surbkeytuple,
                                    msg)))

    def populate_broker_lists(self, source=None):
        if source == None:
            source = self.public_key_server

        def unhexlify_values(a_dict):
            for x in a_dict.keys():
                a_dict[x] = unhexlify(a_dict[x])
            return a_dict

        def get_db_list(source, client):
            dbs_dict_raw = client.broker_comm.getDBList({
                'ip': source['ip'],
                'port': source['port']
            })
            dbs_dict_raw = unhexlify_values(dbs_dict_raw)
            dbs_dict = {}
            for index, (key, value) in enumerate(dbs_dict_raw.items()):
                dbs_dict[index] = (key, value)
            return dbs_dict

        def get_mixnode_list(source, client):
            mixnodes_dict = client.broker_comm.getMixNodeList({
                'ip':
                source['ip'],
                'port':
                source['port']
            })
            mixnodes_dict = unhexlify_values(mixnodes_dict)
            return mixnodes_dict

        self.mixnode_list = get_mixnode_list(source, self)
        self.db_list = get_db_list(source, self)

    def create_db_message(self, index, settings):
        msg = {
            'index': index,
            'pir_xor': settings['pir_xor'],
            'request_type': settings['request_type'],
            'pk': settings['pk'],
            'nymtuple': None
        }
        return msg

    def create_db_destination(self, destination, port):
        try:

            destination = self.db_list[destination]
            destination = (destination[0], destination[1], port)
            key = EcPt.from_binary(destination[1],
                                   getGlobalSphinxParams().group.G)
            return (destination, key)
        except Exception as e:
            raise Exception(
                'Requested database not present or named incorrectly. {} not found. Error {}'
                .format(destination, e))

    def package_message(self,
                        index,
                        db,
                        pir_xor,
                        portEnum,
                        request_type=RequestType.push_to_db.value,
                        mix_subset=5,
                        session_name=None):

        self.public_key, self.private_key = self.encryptor.keyGenerate(
            session_name)
        self.session_name = session_name

        def json_encode(arguments):
            return json.dumps(dict(arguments))

        def prepare_forward_message(mixnodes_dict, message, dest, key,
                                    portEnum):
            params = getGlobalSphinxParams()
            group = params.group.G
            use_nodes_forward = rand_subset(mixnodes_dict.keys(),
                                            SecurityParameters.NUMBER_OF_MIXES)
            use_nodes_backward = rand_subset(
                mixnodes_dict.keys(), SecurityParameters.NUMBER_OF_MIXES)
            nodes_routing_forward = list(map(Nenc, use_nodes_forward))
            nodes_routing_backward = list(map(Nenc, use_nodes_backward))
            pks_chosen_nodes_forward = [
                EcPt.from_binary(mixnodes_dict[key], group)
                for key in use_nodes_forward
            ]
            pks_chosen_nodes_backward = [
                EcPt.from_binary(mixnodes_dict[key], group)
                for key in use_nodes_backward
            ]
            surbid, surbkeytuple, nymtuple = create_surb(
                params, nodes_routing_backward, pks_chosen_nodes_backward,
                self.ip)
            self.surbDict[surbid] = {'surbkeytuple': surbkeytuple}
            message['nymtuple'] = nymtuple
            message = encode(message)
            json_msg = self.encryptForDB(message, key, self.session_name)
            print(json_msg, len(json_msg))
            header, delta = create_forward_message(params,
                                                   nodes_routing_forward,
                                                   pks_chosen_nodes_forward,
                                                   dest, json_msg)
            return (header, delta, use_nodes_forward[0], surbid,
                    use_nodes_backward[-1])

        if len(self.mixnode_list) == 0:
            print("There are no mix-nodes available.")
            return

        if len(self.db_list) == 0:
            print("There are no databases available.")
            return
        db_dest, key = self.create_db_destination(db, portEnum.db.value)
        message = self.create_db_message(
            index, {
                'pir_xor': pir_xor,
                'request_type': request_type,
                'pk': self.public_key
            })
        header, delta, first_mix, surbid, mix_to_poll = prepare_forward_message(
            self.mixnode_list, message, db_dest, key, portEnum)
        self.surbDict[surbid]['index'] = index
        self.surbDict[surbid]['source'] = mix_to_poll
        self.surbDict[surbid]['key'] = self.private_key
        json_data, dest = RequestCreator().post_msg_to_mix(
            {
                'ip': first_mix,
                'port': portEnum.mix.value
            }, {
                'header': header,
                'delta': delta
            })
        if Debug.dbg is True:
            dest['ip'] = b'0.0.0.0'
        return (json_data, dest)
Ejemplo n.º 24
0
class Decryptor:
    encryptor = Encryptor()

    def main(self):
        #creating dataset for the system
        network = list()
        dataset = self.getDataset()
        for i in range(7):
            print("Training Decryptor for bit {} initiated".format(i + 2))
            if i == 0 or i == 1 or i == 2:
                layers = [8, 9, 7, 1]
            elif i == 3 or i == 4 or i == 6:
                layers = [8, 10, 9, 1]
            else:
                layers = [8, 9, 3, 1]
            l_rate = 1.0
            epochs = 10000
            network = self.encryptor.createEncryptor(dataset[i], layers,
                                                     l_rate, epochs)
            name = './network/decryptor/network_bit_' + str(i + 2) + '.json'
            with io.open(name, 'w', encoding='utf8') as outfile:
                str_ = json.dumps(network,
                                  indent=4,
                                  sort_keys=True,
                                  separators=(',', ': '),
                                  ensure_ascii=False)
                outfile.write(to_unicode(str_))
            self.checkEfficiency(network, dataset[i])

    def getDataset(self):
        final_temp = list()
        with open('./data/languageDecryptor.json') as data_file:
            temp1 = json.load(data_file)

        with open('./data/languageDecryptor.json') as data_file:
            temp2 = json.load(data_file)

        with open('./data/languageDecryptor.json') as data_file:
            temp3 = json.load(data_file)

        with open('./data/languageDecryptor.json') as data_file:
            temp4 = json.load(data_file)

        with open('./data/languageDecryptor.json') as data_file:
            temp5 = json.load(data_file)

        with open('./data/languageDecryptor.json') as data_file:
            temp6 = json.load(data_file)

        with open('./data/languageDecryptor.json') as data_file:
            temp7 = json.load(data_file)

        for i in range(100):
            temp1[i][-1] = temp1[i][-1][1:2]
            temp2[i][-1] = temp2[i][-1][2:3]
            temp3[i][-1] = temp3[i][-1][3:4]
            temp4[i][-1] = temp4[i][-1][4:5]
            temp5[i][-1] = temp5[i][-1][5:6]
            temp6[i][-1] = temp6[i][-1][6:7]
            temp7[i][-1] = temp7[i][-1][7:]

        print(temp1)
        final_temp.append(temp1)
        final_temp.append(temp2)
        final_temp.append(temp3)
        final_temp.append(temp4)
        final_temp.append(temp5)
        final_temp.append(temp6)
        final_temp.append(temp7)
        return final_temp

    def checkEfficiency(self, network, dataset):
        c = 0
        for j in dataset:
            k = self.encryptor.predict(network, j, 0)
            s = ""
            k = list(map(str, k))
            k = s.join(k)
            p = j[-1]
            s = ""
            p = list(map(str, p))
            p = s.join(p)
            if (k != p):
                c += 1
        print("Efficiency of this decryptor is " + str(c) + " %")
Ejemplo n.º 25
0
if(choice == '1'):

    inputEmail = input("Enter email address: ")
    inputPassword = input("Enter password: "******"Logging in user: "******"Enter email address: ")
        inputPassword = input("Enter password: "******"Input options: \n\t1: Send message \n\t2: Check messages \n\t3: Logout\n")
        option = input("Input choice: ")

        if(option == '1'):                                        #send message
            recipient = input("Enter recipient email: ")
            msg = input("Enter message:\t")
            encryptedMsg = myEncryptor.encrypt(msg)             #encrypt message before sending
            myClient.postMsg(chatURL, recipient, encryptedMsg)  #send encrypted message

        elif(option == '2'):                                        #check messages
            responseData = myClient.getMsg(chatURL)               #send get request
Ejemplo n.º 26
0
 def set_server_symmetric_key(cls, symmetric_key):
     cls.get_instance(
     ).server_symmetric_key = Encryptor.asymmetric_decrypt_message(
         key=cls.get_instance().client_private_key, message=symmetric_key)
     print('Server symmetric key: ',
           cls.get_instance().server_symmetric_key)
Ejemplo n.º 27
0
from encryptor import Encryptor
from disks import Disks
from constants import SHIFT

if __name__ == '__main__':

    text = 'Some encrypted tex'
    discs = Disks().discs

    out = Encryptor().jefferson_encryption(text, discs, SHIFT, reverse=False)
    print(out)

    def __init__(self):

        self.carriageReturn = chr(13)
        self._data = Encryptor.getData(Encryptor())
Ejemplo n.º 29
0
 def encrypt_button(self, passwd):
     response = messagebox.askyesno("Enrypt", "Are you sure?")
     key = passwd.encode('UTF-8')
     enc = Encryptor(key)
     enc.encrypt_file(self.filename)
     pass
Ejemplo n.º 30
0
class MixNode():
    def __init__(self, broker_config, pool_size=3):
        self.private_key = None
        self.public_key = None
        self.ip = None
        self.params = getGlobalSphinxParams()
        self.network_sender = NetworkSender()
        self.broker_config = broker_config
        self.encryptor = Encryptor(self.params.group)
        self.db_list = None
        self.broker_comm = BrokerCommunicator()
        self.client_cache = {}
        self.mix_pool = MixPool(pool_size)
        self.client_backlog = set()

    def handlePool(self, pool_lock):
        while (1):
            with pool_lock:
                # print("POOL SIZE: {}".format(len(self.mix_pool.getContents())))
                items_to_send = self.mix_pool.getSelection()
            for entry in items_to_send:
                json_data, destination = entry
                if Debug.dbg:
                    destination['ip'] = '0.0.0.0'
                print("SENDING")
                self.network_sender.send_data(json_data, destination)
            time.sleep(0.05)

    def handleCache(self, backlog_lock):
        while 1:
            toRemove = []
            with backlog_lock:
                # print('Cache size: {}'.format(len(self.client_cache)))
                for entry in self.client_backlog:
                    client_id, socket = entry
                    if client_id in self.client_cache:
                        toRemove.append(entry)
                        start = time.time()
                        operation = ''
                        response = self.client_cache.get(client_id)
                        response = encode({
                            "id": client_id,
                            "response": response
                        })
                        socket.sendall(response)
                        self.client_cache.pop(client_id)
                        operation = '[CLIENT_POLL] send'
                        end = time.time()
                        timestamp = datetime.fromtimestamp(
                            end - start).strftime('%M:%S:%f')
                        logger.log_info(
                            '[TIME] MIX LISTENER {} TOOK {}'.format(
                                operation, timestamp))
                for entry in toRemove:
                    self.client_backlog.remove(entry)
            time.sleep(0.05)

    def pool_item(self, item):
        self.mix_pool.addInPool(item)

    def getDbList(self):
        def unhexlify_values(a_dict):
            for x in a_dict.keys():
                a_dict[x] = unhexlify(a_dict[x])
            return a_dict

        def _get_db_list(source):
            dbs_dict_raw = self.broker_comm.getDBList({
                'ip': source['ip'],
                'port': source['port']
            })
            dbs_dict_raw = unhexlify_values(dbs_dict_raw)
            dbs_dict = {}
            for index, (key, value) in enumerate(dbs_dict_raw.items()):
                dbs_dict['DB{}'.format(index)] = (key, value)
            return dbs_dict

        if self.db_list == None:
            source = {
                'ip': self.broker_config['pkserver'],
                'port': self.broker_config['port']
            }
            self.db_list = _get_db_list(source)
        return self.db_list

    def publish_key(self):
        def prepare_sending_pk(public_key, server_config):
            key_server_ip = server_config['pkserver']
            port = server_config['port']
            try:
                response = os.system("ping -c 1 " + key_server_ip)
                if response != 0:
                    raise ValueError(
                        "Server: {} cannot be reached. The key was not published"
                        .format(self.ip))
                else:
                    request_creator = RequestCreator()
                    json_data, destination = request_creator.post_mix_key_request(
                        {
                            'ip': key_server_ip,
                            'port': port
                        }, {
                            'id': public_key[0],
                            'pk': public_key[2]
                        })
                    return (json_data, destination)
            except Exception as error:
                print("Unexpected error: {}".format(error))
                return None
            return None

        self.public_key, self.private_key = self.encryptor.keyGenerate(
            self.getIp())
        json_data, destination = prepare_sending_pk(self.public_key,
                                                    self.broker_config)
        # publish key
        response = self.network_sender.send_data(json_data, destination)
        return response

    def getIp(self):
        if self.ip is None:
            self.ip = getPublicIp()
        return self.ip

    def process(self, header, delta, cb=None):
        private_key = self.private_key
        ret = sphinx_process(self.params, private_key.x, header, delta)
        (tag, info, (header, delta)) = ret
        routing = PFdecode(self.params, info)
        if routing[0] == Relay_flag:
            flag, addr = routing
            return (Relay_flag, addr, header, delta)
        elif routing[0] == Dest_flag:
            dest, msg = receive_forward(self.params, delta)
            return (Dest_flag, msg, dest, None)
        elif routing[0] == Surb_flag:
            flag, dest, myid = routing
            return (flag, dest, myid, delta)