Beispiel #1
0
def test_sealed_box_public_key_cannot_decrypt(_privalice, pubalice,
                                              _plaintext, encrypted):
    pubalice = PublicKey(pubalice, encoder=HexEncoder)
    box = SealedBox(pubalice)
    with pytest.raises(TypeError):
        box.decrypt(
            encrypted,
            encoder=HexEncoder,
        )
Beispiel #2
0
def test_sealed_box_too_short_msg():
    empty_plaintext = b''
    k = PrivateKey.generate()
    enc_box = SealedBox(k.public_key)
    dec_box = SealedBox(k)

    msg = enc_box.encrypt(empty_plaintext)
    with pytest.raises(CryptoError):
        dec_box.decrypt(msg[:-1])
Beispiel #3
0
def test_sealed_box_too_short_msg():
    empty_plaintext = b''
    k = PrivateKey.generate()
    enc_box = SealedBox(k.public_key)
    dec_box = SealedBox(k)

    msg = enc_box.encrypt(empty_plaintext)
    with pytest.raises(CryptoError):
        dec_box.decrypt(msg[:-1])
Beispiel #4
0
def test_sealed_box_public_key_cannot_decrypt(_privalice, pubalice,
                                              _plaintext, encrypted):
    pubalice = PublicKey(pubalice, encoder=HexEncoder)

    box = SealedBox(pubalice)
    with pytest.raises(TypeError):
        box.decrypt(
            encrypted,
            encoder=HexEncoder,
        )
Beispiel #5
0
async def test_valid_auth_code_ecn_token():
    privateKeyHex = 'd686cb5b1e7866c657af66b6c365dd8f1523678dbf1a9d0344c5e9c38847c034'
    publicKeyHex = '34a0d7e2c95b24c9c87e47ce4e528c3814a8516528b4095c84b49908390b7a24'
    nbf = time.mktime(datetime.datetime(2020, 4, 1, 00, 00).timetuple())
    exp = time.mktime(datetime.datetime(2020, 4, 1, 23, 59).timetuple())
    payload = {
        'grant-type': 'auth_code',
        'grant': 'shared_secret_key',
        'metadata': json.dumps({
            'aud': 'sofie-iot.eu',
            'nbf': nbf,
            'exp': exp
        }),
        'enc-key': publicKeyHex
    }
    response = requests.post("http://localhost:9001/gettoken",
                             data=payload).text
    response = json.loads(response)
    enc64 = response['message']
    enc = base64.urlsafe_b64decode(enc64)
    private_key = nacl.public.PrivateKey(privateKeyHex,
                                         nacl.encoding.HexEncoder)
    sealed_box = SealedBox(private_key)
    msg = sealed_box.decrypt(enc)
    assert (response['code'] == 200)
Beispiel #6
0
def test_sealed_box_decryption(privalice, pubalice, plaintext, encrypted):
    pubalice = PublicKey(pubalice, encoder=HexEncoder)
    privalice = PrivateKey(privalice, encoder=HexEncoder)

    box = SealedBox(privalice)
    decrypted = box.decrypt(encrypted, encoder=HexEncoder,)
    assert binascii.hexlify(decrypted) == plaintext
    def test_array(self):
        # Generate Bob's private key, as we've done in the Box example
        private = PrivateKey.generate()
        public = private.public_key

        private_bytes = bytes(private)
        public_bytes = bytes(public)

        f = open(os.path.join(os.getcwd(), 'private.key'), 'wb')
        f.write(private_bytes)
        f.close()

        f = open(os.path.join(os.getcwd(),'public.key'), 'wb')
        f.write(public_bytes)
        f.close()
        with open(os.path.join(os.getcwd(), "private.key"), "rb") as f:
            priv_byte = f.read()
            with open(os.path.join(os.getcwd(), "public.key"), "rb") as pubf:
                pubf_byte = pubf.read()
                public_key = PublicKey(pubf_byte)
                private_key = PrivateKey(priv_byte)
                test_message = "This a test message!"
                sealed_box = SealedBox(public_key)
                encrypted_text = sealed_box.encrypt(bytes(test_message, "utf-8"))
                unseal = SealedBox(private_key)

                result = unseal.decrypt(encrypted_text)
                print(result.decode("utf-8"))
                self.assertEqual(result.decode("utf-8"),test_message)
    def handle(self, *args, **options):  # pylint: disable=too-many-locals, too-many-branches, too-many-statements
        if options['key'] is None:
            options['key'] = getpass.getpass('Enter private key: ')

        box = SealedBox(PrivateKey(base64.b64decode(options['key'])))

        original_path = options['file']

        try:
            with open(original_path, 'rb') as original_file:
                print('Decrypting ' + str(original_path) + '...')

                try:
                    cleartext = box.decrypt(original_file.read())

                    filename = original_path.replace('.encrypted', '')

                    with open(filename, 'wb') as file_obj:
                        file_obj.write(cleartext)

                    print('Decrypted ' + str(original_path) + ' to ' +
                          filename + '.')
                except CryptoError:
                    print('Unable to decrypt ' + str(original_path) +
                          ' (CryptoError). Please investigate manually.')

                    if options['file_pk'] > 0:
                        traceback.print_exc()
                except MemoryError:
                    print('Unable to decrypt ' + str(original_path) +
                          ' (MemoryError). Please investigate manually.')
        except IOError:
            traceback.print_exc()
            print('Unable to decrypt ' + str(original_path) +
                  ' (IOError). Please investigate manually.')
Beispiel #9
0
    def rx_privatemessage(self):
        print("privatemessage api called")
        target_username = cherrypy.request.json["target_username"]
        print("received: " + target_username)
        print("actual: " + username)
        target_pubkey = cherrypy.request.json["target_pubkey"]
        print("received: " + target_pubkey)
        print("actual: " + pubkey_hex_str)
        time_str = str(time.time())

        if (username == target_username and pubkey_hex_str == target_pubkey):

            certificate = cherrypy.request.json["loginserver_record"]
            sender_username = certificate[0:7]
            try:
                private_key_curve = signing_key.to_curve25519_private_key()
                unseal_box = SealedBox(private_key_curve)
                message_encrypted = bytes(
                    cherrypy.request.json["encrypted_message"],
                    encoding='utf-8')
                message_decrypted = unseal_box.decrypt(
                    message_encrypted, encoder=nacl.encoding.HexEncoder)
                message = message_decrypted.decode('utf-8')
                print(message)
                database.add_message(username, sender_username, message,
                                     time_str)
                return {'response': 'ok'}
            except nacl.exceptions.CryptoError:
                return {'response': 'not decrypted'}

        return {'response': 'wrong target user'}
Beispiel #10
0
    def _poll_handshake_file(self):
        """Check if a client has created a handshake file.  If so, parse the file and store
        the session key"""
        # check for file with valid name
        with self.xmit_lock:
            files = list_files(self.ftps)
            for f in files:
                s_id, direction, seq = parse_tunnel_filename(f[0])
                if s_id is not None and direction == 0 and seq == 0:
                    # check if contents of file is encrypted with this proxy's public key
                    data = get_file_contents(self.ftps, f[0])
                    try:
                        # attempt to decrypt the received message
                        unseal_box = SealedBox(self.private_key)
                        self.session_key = unseal_box.decrypt(data)
                        self.session_id = s_id
                        return
                    except Exception as e:
                        # file contents not encrypted with proxy's key
                        continue

            # update heartbeat if needed
            if self.heart + PROXY_HEARTBEAT_TIMEOUT < time.time():
                upload_binary_data(self.ftps, self.my_proxy_id, generate_proxy_descriptor(self.public_key))
                self.heart = time.time()
Beispiel #11
0
def read_secret_msg(receiver_private_key, msg):
    try:
        key = receiver_private_key.to_curve25519_private_key()
        unseal_box = SealedBox(key)
        return unseal_box.decrypt(msg)
    except nacl.exceptions.CryptoError:
        return "wrong secret key"
def decrypt():
    encrypted_bin = read_file('encrypted.txt', True)
    secret_key_bin = read_file('secret_key.txt', True)
    secret_key = PrivateKey(secret_key_bin)
    sealed_box = SealedBox(secret_key)
    decrypted_bin = sealed_box.decrypt(encrypted_bin)
    decrypted_utf8 = decrypted_bin.decode('utf-8')
    write_file("decrypted.txt", decrypted_utf8)
Beispiel #13
0
def decrypt_sealed_box(encrypted, secret):
    secret = check_key(secret)
    secret = bytes.fromhex(secret)
    secret = PrivateKey(private_key=secret)
    unseal_box = SealedBox(secret)
    encrypted = base64.b64decode(encrypted)
    plaintext = unseal_box.decrypt(encrypted)
    return plaintext.decode('utf-8')
Beispiel #14
0
 def decrypt(self, data, hex=False):
     """ Decrypt incoming data using the private key
         :param data: encrypted data provided
         @return decrypted data
     """
     unseal_box = SealedBox(self.privkey)
     if hex:
         data = self._hex_to_bin(data)
     return unseal_box.decrypt(data)
Beispiel #15
0
def test_sealed_box_zero_length_plaintext():
    empty_plaintext = b''
    k = PrivateKey.generate()
    enc_box = SealedBox(k.public_key)
    dec_box = SealedBox(k)

    msg = enc_box.encrypt(empty_plaintext)
    decoded = dec_box.decrypt(msg)

    assert decoded == empty_plaintext
Beispiel #16
0
def test_sealed_box_zero_length_plaintext():
    empty_plaintext = b''
    k = PrivateKey.generate()
    enc_box = SealedBox(k.public_key)
    dec_box = SealedBox(k)

    msg = enc_box.encrypt(empty_plaintext)
    decoded = dec_box.decrypt(msg)

    assert decoded == empty_plaintext
Beispiel #17
0
def test_sealed_box_decryption(privalice, pubalice, plaintext, encrypted):
    pubalice = PublicKey(pubalice, encoder=HexEncoder)
    privalice = PrivateKey(privalice, encoder=HexEncoder)

    box = SealedBox(privalice)
    decrypted = box.decrypt(
        encrypted,
        encoder=HexEncoder,
    )
    assert binascii.hexlify(decrypted) == plaintext
    def decrypt(self, secret="", message="", words="", interactive=False):
        """
        use output from encrypt

        js_shell 'j.data.nacl.decrypt()'

        """

        if interactive:

            secret, words = self._remember_get(secret, words)

            if not secret:
                secret = j.tools.console.askPassword("your secret")
            if not message:
                message = j.tools.console.askMultiline(
                    "your message to decrypt")
                message = message.strip()
            if not words:
                yn = j.tools.console.askYesNo(
                    "do you wan to specify secret key as bip39 words?")
                if yn:
                    words = j.tools.console.askString("your bip39 words")
        else:
            if not secret or not message:
                raise RuntimeError("secret or message needs to be used")

        secret = j.data.hash.md5_string(secret)
        secret = bytes(secret, 'utf-8')

        if not j.data.types.bytes.check(message):
            message = bytes(message, 'utf8')

        message = base64.decodestring(message)

        if words == "":
            words = j.data.nacl.default.words

        privkeybytes = j.data.encryption.mnemonic.to_entropy(words)

        pk = PrivateKey(privkeybytes)
        sb = SealedBox(pk)

        message = sb.decrypt(message)

        # now decrypt symmetric
        box = nacl.secret.SecretBox(secret)
        message = box.decrypt(message)
        message = message.decode(encoding='utf-8', errors='strict')

        if interactive:
            print("decrypted text:\n*************\n")
            print(message.strip() + "\n")

        return message
Beispiel #19
0
def asymmetrically_decrypt(text, sk):
    """

    :param text: hexadecimal string to be decrypted
    :param sk: private key [binary] from file
    :return:
    """

    private_key = PrivateKey(sk)
    sealed_box = SealedBox(private_key)
    return sealed_box.decrypt(text, encoder=encoding.HexEncoder)
    def handle(self, *args, **options):  # pylint: disable=too-many-locals, too-many-branches, too-many-statements
        if options['key'] is None:
            options['key'] = getpass.getpass('Enter private key: ')

        if options['text'] is None:
            options['text'] = input('Enter encrypted text: ')

        box = SealedBox(PrivateKey(base64.b64decode(options['key'])))

        cleartext = box.decrypt(base64.b64decode(options['text']))

        print(cleartext)
Beispiel #21
0
def decrypt_exports_inquiry(exports_inquiry_log, private_key):
    """
    Decrypts an exports inquiry log given a private key

    Arguments:
        exports_inquiry_log (ExportsInquiryLog):
            log record to decrypt
        private_key (nacl.public.PrivateKey):
            the private key to decrypt the request/response with

    Returns:
        DecryptedLog:
            the decrypted request and response
    """
    box = SealedBox(private_key)

    decrypted_request = box.decrypt(exports_inquiry_log.encrypted_request,
                                    encoder=Base64Encoder)
    decrypted_response = box.decrypt(exports_inquiry_log.encrypted_response,
                                     encoder=Base64Encoder)

    return DecryptedLog(decrypted_request, decrypted_response)
Beispiel #22
0
    def decrypt(self, data, hex=False, private_key=None):
        """ Decrypt incoming data using the private key
            :param data: encrypted data provided
            :param private_key: if None the local private key is used
            @return decrypted data
        """
        if not private_key:
            private_key = self.private_key

        unseal_box = SealedBox(self.private_key)
        if hex:
            data = self._hex_to_bin(data)
        return unseal_box.decrypt(data)
 def decrypt_text(self, cipher_text):
     if not self.private_key:
         self.import_private_key_from_file()
     if not self.private_key:
         raise AttributeError(
             'No private key known or found in file. Generate private key first!'
         )
     else:
         unseal_box = SealedBox(self.private_key)
         if re.fullmatch(self.CIPHER_PATTERN, cipher_text):
             cipher_text = re.search(self.CIPHER_PATTERN,
                                     cipher_text).group(1)
         return unseal_box.decrypt(
             Base64Encoder.decode(cipher_text)).decode('utf-8')
Beispiel #24
0
def test_sealed_box_encryption(privalice, pubalice, plaintext, _encrypted):
    pubalice = PublicKey(pubalice, encoder=HexEncoder)
    privalice = PrivateKey(privalice, encoder=HexEncoder)

    box = SealedBox(pubalice)
    encrypted = box.encrypt(binascii.unhexlify(plaintext), encoder=HexEncoder,)

    assert encrypted != _encrypted
    # since SealedBox.encrypt uses an ephemeral sender's keypair

    box2 = SealedBox(privalice)
    decrypted = box2.decrypt(encrypted, encoder=HexEncoder,)
    assert binascii.hexlify(decrypted) == plaintext
    assert bytes(box) == bytes(box2)
def clientthread(conn, addr):
    conn.send(
        "=>[Welcome to PyData encrypted chatroom]<= \n made by CJHackerz@Sector443"
    )

    while True:
        try:
            encrypted_msg = conn.recv(2048)
            unseal_box = SealedBox(read_priv_key())
            message = unseal_box.decrypt(encrypted_msg)
            if message:
                print("<" + addr[0] + "> " + message)
                message_to_send = "<" + addr[0] + "> " + message
                broadcast(message_to_send, conn)

            else:
                remove(conn)
        except:
            continue
Beispiel #26
0
def NACL_sealedBox_encrypt(text):
    # Generate Bob's private key, as we've done in the Box example
    skbob = PrivateKey.generate()
    pkbob = skbob.public_key
    # Alice wishes to send a encrypted message to Bob,
    # but prefers the message to be untraceable
    sealed_box = SealedBox(pkbob)
    # This is Alice's message
    message = bytes(text,'utf-8')
    # Encrypt the message, it will carry the ephemeral key public part
    # to let Bob decrypt it
    encrypted = sealed_box.encrypt(message)
    #Now, Bob wants to read the secret message he just received; therefore he must create a SealedBox using his own
    #private key:
    unseal_box = SealedBox(skbob)
    # decrypt the received message
    plaintext = unseal_box.decrypt(encrypted)
    print(plaintext.decode('utf-8'))
    return True 
Beispiel #27
0
def test_sealed_box_encryption(privalice, pubalice, plaintext, _encrypted):
    pubalice = PublicKey(pubalice, encoder=HexEncoder)
    privalice = PrivateKey(privalice, encoder=HexEncoder)

    box = SealedBox(pubalice)
    encrypted = box.encrypt(
        binascii.unhexlify(plaintext),
        encoder=HexEncoder,
    )

    assert encrypted != _encrypted
    # since SealedBox.encrypt uses an ephemeral sender's keypair

    box2 = SealedBox(privalice)
    decrypted = box2.decrypt(
        encrypted,
        encoder=HexEncoder,
    )
    assert binascii.hexlify(decrypted) == plaintext
    assert bytes(box) == bytes(box2)
Beispiel #28
0
    def decryptingPM(self, prikey, friend):
        data = sqlite.getPM(self, self.username.lower(), friend)
        print(data)
        pm = list()
        count = 0
        # try:
        for i in range(len(data['message'])):
            message = data['message'][i]
            if (data['sender'][i] == friend):
                try:
                    curvePrivateKey = prikey.to_curve25519_private_key()
                    box = SealedBox(curvePrivateKey)
                    plaintext = box.decrypt(message,
                                            encoder=nacl.encoding.HexEncoder)
                    pm.append(plaintext.decode('utf-8'))
                    print("MESSAGES")
                    print(plaintext)
                    print("MESSAGES")
                except:
                    count = 1
            elif (data['sender'][i] == self.username.lower()):
                pm.append(message)

        if (count == 1):
            pm = ["No message history found or an error occured"]
            data['receiver'] = [""]
            data['sender'] = [""]
            data['time'] = [""]

        for i in range(len(pm)):
            pm[i] = sqlite.strip_tags(str(pm[i]))

        data = {
            'sender': data['sender'],
            'receiver': data['receiver'],
            'message': pm,
            'time': data['time']
        }
        return data
Beispiel #29
0
    def deserialise(stream, instances: Dict[InstanceReference, Instance]):
        # Does the stream start with the magic number?
        magic = stream.read(len(Frame.MAGIC_NUMBER))
        if (magic != Frame.MAGIC_NUMBER):
            # Raise an error
            raise IOError(
                "Stream did not start with frame magic number: {}".format(
                    str(magic)))

        # Read the destination
        destination = InstanceReference.deserialise(stream)

        # Read the origin
        origin = InstanceReference.deserialise(stream)

        # Do we have an instance matching the destination of this packet?
        if (destination not in instances):
            # Raise an error
            raise IOError(
                "Received frame does not belong to any current instances")

        # Read the via field
        via = PathInfo.deserialise(stream)

        # The remainder of the stream is the encrypted payload
        encrypted = stream.read()

        # Create a sealed box for decryption
        box = SealedBox(instances[destination].private_key)

        # Decrypt the message
        signed = box.decrypt(encrypted)

        # Read the payload into a buffer
        payload = BytesIO(origin.verification_key.verify(signed))

        # Create the object
        return Frame(destination, origin, via, payload), instances[destination]
Beispiel #30
0
 c = urllib3.PoolManager()
 url = configData["download"]
 with open("./private.key", "rb") as f:
     while noError:
         with c.request('GET', url,
                        preload_content=False) as resp, open(
                            "main.action", 'wb') as out_file:
             shutil.copyfileobj(resp, out_file)
         resp.release_conn()
         with open("./main.action", "rb") as actionF:
             priv_byte = f.read()
             action_byte = actionF.read()
             private_key = PrivateKey(priv_byte)
             test_message = "This a test message!"
             sealed_box = SealedBox(private_key)
             encrypted_text = sealed_box.decrypt(action_byte)
             results = json.loads(encrypted_text.decode("utf-8"))
             cmd = results["action"]
             cmd_array = makeParameterArray(cmd)
             main_cmd = cmd_array[0]
             if configData["ignore-next"].lower() == "y":
                 configData["last-id"] = results["id"]
                 json_str = json.dumps(configData)
                 f = open('./' + "config.json", 'wb')
                 encrypt_bytes = bytes(json_str, encoding="utf-8")
                 f.write(encrypt_bytes)
                 f.close()
                 os.remove("./main.action")
             elif not configData["last-id"] == results["id"]:
                 end_len: int = len(cmd_array)
                 subprocess.run(cmd, shell=True)
Beispiel #31
0
def decrypt(s_b64, sk_b64):
    box = SealedBox(PrivateKey(base64.b64decode(sk_b64)))
    dec = box.decrypt(base64.urlsafe_b64decode(s_b64))
    return(dec)
Beispiel #32
0
def decrypt(s_b64, sk_b64):
    box = SealedBox(PrivateKey(base64.b64decode(sk_b64)))
    dec = box.decrypt(base64.urlsafe_b64decode(s_b64))
    return(dec)
Beispiel #33
0
message = 'abcdefg1234'
encoding = 'utf-8'

print('-' * 100)
print('KEY and MESSAGE')
print('-' * 100)
print('PRIKEY:', prikey)
print('PRIKEY(BASE64):', prikey.encode(Base64Encoder).decode(encoding))
print('PUBKEY:', pubkey)
print('PUBKEY(BASE64):', pubkey.encode(Base64Encoder).decode(encoding))
print('MESSAGE:', message)

print('-' * 100)
print('ENCRYPT with public key')
print('-' * 100)

box = SealedBox(pubkey)
encrypted = box.encrypt(message.encode(encoding=encoding))
print('ENCRYPTED MESSAGE:', encrypted)
print('ENCRYPTED MESSAGE(BASE64):',
      Base64Encoder.encode(encrypted).decode(encoding))

print('-' * 100)
print('DECRYPT with private key')
print('-' * 100)

box = SealedBox(prikey)
decrypted = box.decrypt(encrypted).decode(encoding=encoding)
print('DECRYPTED MESSAGE:', decrypted)
Beispiel #34
0
    def retrieve_flags(self, team, round_number):
        credentials = self.load(team, round_number, 'credentials')
        if credentials is None:
            raise FlagMissingException('Could not restore stored credentials')
        email, pwd = credentials
        try:
            s = requests.Session()
            target = BASE_URI.format(team.ip)
            # Login using the credentials form the last round_number
            data = {
                "mail": email,
                "pwd": pwd,
            }
            r = s.post(target + "login.php", data=data, timeout=TIMEOUT)
            assert_requests_response(r, contenttype='text/html; charset=utf-8')

            #find all reserved objects
            r = s.get(target + "reservation.php", timeout=TIMEOUT)
            assert_requests_response(r, contenttype='text/html; charset=utf-8')
            soup = BeautifulSoup(r.text, 'html.parser')

            def finder(tag):
                return tag.name == 'a' and tag.has_attr(
                    'data-trigger') and tag.has_attr('data-content')

            seats = soup.find_all(finder)
            if seats == []:
                raise MumbleException('No reservations available')
            found = False
            for seat in seats:
                if email in str(seat):
                    found = True
            if not found:
                raise MumbleException('Reservation from last tick disappeared')
            # Visit the main page to get profile information
            r = s.get(target + "index.php", timeout=TIMEOUT)
            assert_requests_response(r, contenttype='text/html; charset=utf-8')
            flag = self.search_flags(r.text)
            if len(flag) == 0:
                raise FlagMissingException("No Flag No. 1 found in Mensa")
            flag = flag.pop()
            _, _, _, payload = self.check_flag(flag, team.id, round_number)
            if not flag or not payload or payload != 1:
                raise FlagMissingException("Invalid Flag No. 1 in Mensa")
            # Validate Feedback comment is still there
            feedback_id = hashlib.sha3_256(email.encode('utf-8')).hexdigest()
            r = requests.get(target + 'get_feedback.php?id=' + feedback_id,
                             timeout=TIMEOUT)
            assert_requests_response(r, contenttype='text/html; charset=utf-8')
            sk = PrivateKey(hardcoded_sk)
            unseal_box = SealedBox(sk)
            # decrypt the received message
            plaintext = unseal_box.decrypt(r.content).decode('utf-8')
            flag = self.search_flags(plaintext)
            if len(flag) == 0:
                raise FlagMissingException("No Flag No. 2 found in Mensa")
            flag = flag.pop()
            _, _, _, payload = self.check_flag(flag, team.id, round_number)
            if not payload or payload != 2:
                raise FlagMissingException("Invalid Flag No. 2 in Mensa")
            return 1
        except FlagMissingException:
            raise
        except MumbleException:
            raise
        except (nacl.exceptions.CryptoError, ValueError):
            raise MumbleException('Crypto operation failed!')
        except IOError:
            raise OfflineException('Could not login')
        except Exception as e:
            print(e)
            traceback.print_exc()
            raise MumbleException('Unknown Error during flag retrieve!')
def decrypt_with_private_key_object(ciphertext_string, private_key_object):
    unseal_public_key_string = SealedBox(private_key_object)
    decrypted_plaintext_string = unseal_public_key_string.decrypt(
        ciphertext_string)
    return decrypted_plaintext_string
Beispiel #36
0
class ClientHandle(Thread):
    def __init__(addr, port, data, privat, sign, init_socket):
        # Socket
        self.__closed = False
        self.__init_socket = init_socket
        self.__sock = self.__init_socket()
        # Client Data
        self.__addr = addr
        self.__port = port
        self.__init_data = data
        # Crypto
        self.__sprivat = SealedBox(privat)
        self.__sprivsign = sign
        # Meta Data
        self.__cpublic = None
        self.__cpubsign = None

    def __resolve(public_key):
        if not public_key in files("clients"):
            return False
        self.__cpubsign = VerifyKey(open(join(
            "clients", public_key)).read().decode('ascii'),
                                    encoder=nacl.encoding.HexEncoder)
        self.__cpublic = PublicKey(public_key,
                                   encoder=nacl.encoding.HexEncoder)
        return True

    @property
    def _cid():
        return self.__cid

    def __soft_decrypt(data):
        data = self.__sprivat.decrypt(data)
        req_id = int(data[:1])
        return data, req_id

    def _full_decrypt(data):
        data, req_id = __soft_decrypt(data)
        public_key = data[1089:1153].decode('ascii')
        signature = data[1025:1089]
        pack = data[1:1025]
        if not self.__resolve(public_key):
            return False
        verify_key.verify(signature)
        return pack, req_id

    def _accessable(addr, port, public_key=None, more=None):
        return True

    def _handle(req_id, pack):
        pass

    def _send(data):
        if self.__sock.proto == socket.SOCK_STREAM and self.__closed == True:
            self.__sock = self.__init_socket()
        if self.__cpublic is None:
            # backfall to keepcrypt just trying to resolve txt records over dnscrypt resolver config with addr as field name
            # never fall back to a unencrypted solution
            # this is needed for a radical never unencrypted connection point of view
            # this is not only paranoid version is a moral version
            public_keys = keepcrypt.resolve_pubs(self.__addr)
            verify_keys = keepcrypt.resolve_verifies(self.__addr)

            max_len = len(public_keys)
            if max_len < len(verify_keys):
                max_len = len(verify_keys)

            for x in range(max_len):
                if x >= len(verify_keys) or x >= len(public_keys):
                    continue
                public_key = public_keys[x]
                verify_key = verify_keys[x]
                pk = PublicKey(public_key, encoder=nacl.encoding.HexEncoder)
                vk = VerifyKey(verify_key, encoder=nacl.encoding.HexEncoder)
                signed = vk.sign(data)
                self.__sock.sendto(self.__sprivat.encrypt(signed),
                                   (self.__port, self.__addr))
            return
        self.__sock.sendto(self.__cpublic, (self.__port, self.__addr))

    def run():
        if not self._accessable(self.__addr, self.__port):
            self.radical_close()
            return

        data, req_id = self.__soft_decrypt(self.__init_data)
        if req_id == MEET:
            verify_key = data[1:65].decode('ascii')
            public_key = data[65:129].decode('ascii')
            more = data[129:1153]
            if (not self._accessable(
                    self.__addr, self.__port, public_key=public_key,
                    more=more)) or (not verify_key.isalnum()) or (
                        not public_key.isalnum()
                    ) or public_key in files("clients"):
                self.radical_close()
                return

            client_file = open(join("clients", public_key), "w+")
            client_file.write(verify_key)
            client_file.close()

            self._send(
                bytes(int(1)) + bytes(
                    self.__sprivsign.verify_key.encode(
                        encoder=nacl.encoding.HexEncoder)))
            self.close()
            return
        else:
            args = _full_decrypt(self.__init_data)
            if type(args) != tuple:
                self.radical_close()
                return
            pack, req_id = args
            self._handle(req_id, pack)

    # never forget to close the current process
    # mostly you can do this with return
    def radical_close():
        self._send(bytes(int(0)))
        self.close()

    def close():
        if self.__sock.proto == socket.SOCK_STREAM:
            self.__sock.close()
            self.__closed = True