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)
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_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 #4
0
def test_sealed_box_creation():
    pub = PublicKey(
        b"ec2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798",
        encoder=HexEncoder,
    )
    priv = PrivateKey(
        b"5c2bee2d5be613ca82e377c96a0bf2220d823ce980cdff6279473edc52862798",
        encoder=HexEncoder,
    )
    SealedBox(priv)
    SealedBox(pub)
Beispiel #5
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 complete_distance_verification(self, db_challenge, db_response, epoch, voting_group, distance_result):
        # derive secret key from db_challenge/db_response
        secret_key = db_response  # TODO not quite right but ok

        # kinda shady caching -- *should* return some value that the distance verifier can pass
        if self._cached_voting_group_hash is not None:
            voting_group_hash = self._cached_voting_group_hash
        else:
            voting_group_hash = makehash(voting_group)
            self._cached_voting_group = set(voting_group)
            self._cached_voting_group_hash = voting_group_hash

        # verification
        user_public_key = self.db_to_pk.get(secret_key)
        if user_public_key is None:
            raise Exception('KeyAuthority: could not find DB Key -> PK mapping')

        user_public_key_str = get_key_string(user_public_key)
        if user_public_key_str not in self._cached_voting_group:
            raise Exception('KeyAuthority: user PK not in voting group')
        
        user_token = makehash((epoch, voting_group_hash, user_public_key_str, secret_key))
        pdp = self.signing_key.sign(obj2bytes((distance_result, voting_group_hash, user_token)))
        sdp = self.signing_key.sign(obj2bytes((user_public_key_str, pdp)))
        esdp = SealedBox(user_public_key).encrypt(sdp)
        return esdp
Beispiel #7
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"
Beispiel #8
0
 def asymmetric_decrypt(prv_key, data):
     """
     Perform asymmetric decryption using libsodium sealedbox (Curve25519, XSalsa20-Poly1305)
     """
     prv_key = PrivateKey(prv_key, RawEncoder)
     data = _convert_to_bytes(data)
     return SealedBox(prv_key).decrypt(data)
Beispiel #9
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 #10
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 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 #12
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'}
 def generate_token(self,
                    private_key,
                    metadata=None,
                    enc_key=None,
                    token_type=None):
     claims = {}
     metadata = json.loads(metadata)
     #create token_id
     if 'aud' in metadata:
         claims['aud'] = metadata['aud']
     if 'sub' in metadata:
         claims['sub'] = metadata['sub']
     if 'exp' in metadata:
         claims['exp'] = metadata['exp']
     if 'nbf' in metadata:
         claims['nbf'] = metadata['nbf']
     claims['jti'] = random.getrandbits(256)
     token = jwt.encode(claims, private_key, algorithm='RS256')
     if enc_key:
         public_key = nacl.public.PublicKey(enc_key,
                                            nacl.encoding.HexEncoder)
         sealed_box = SealedBox(public_key)
         token = sealed_box.encrypt(token)
         token = base64.urlsafe_b64encode(token)
     #return 200, {'code':200,'message':token.decode('utf-8')}
     return token, claims
Beispiel #14
0
 def _box():
     try:
         nonce = nacl.utils.random(Box.NONCE_SIZE)
         box = SealedBox(PublicKey(pubKey))
         return box.encrypt(msg, nonce)
     except Exception:
         return
Beispiel #15
0
 def asymmetric_encrypt(pub_key, data):
     """
     Perform asymmetric encryption using libsodium sealedbox (Curve25519, XSalsa20-Poly1305)
     """
     pub_key = PublicKey(pub_key, RawEncoder)
     data = _convert_to_bytes(data)
     return SealedBox(pub_key).encrypt(data)
Beispiel #16
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 #17
0
    def _retrieve_service_generated_cert(self, request, dek_info):
        """

        :param CertificateRequest request:
        :param EdgeEncryptionKey dek_info:
        :rtype: Certificate
        """
        box = SealedBox(dek_info.public_key)
        encrypted_key_pass = box.encrypt(request.key_password)
        body = {
            'exportFormat':
            'PEM',
            'encryptedPrivateKeyPassphrase':
            base64.b64encode(encrypted_key_pass).decode('utf-8'),
            'encryptedKeystorePassphrase':
            '',
            'certificateLabel':
            ''
        }
        url = URLS.CERTIFICATE_KEYSTORE_BY_ID.format(request.cert_guid)
        status, data = self._post(url, data=body)
        if status not in (HTTPStatus.OK, HTTPStatus.CREATED,
                          HTTPStatus.ACCEPTED):
            log.error("Some error")
            raise VenafiError

        cert, chain, private_key = zip_to_pem(data, request.chain_option)
        return Certificate(cert=cert, chain=chain, key=private_key)
Beispiel #18
0
    def generate_zos_keys(self, node_public_key):
        """
        Generate a new set of wireguard key pair and encrypt
        the private side using the public key of a 0-OS node.

        This implementation match the format 0-OS except to be able
        to read wireguard keys into network reservations.

        :param node_public_key: hex encoded public key of 0-OS node.
                                This is the format you find in the explorer
        :type node_public_key: str
        :return: tuple containing 3 fields (private key, private key encrypted, public key)
        :rtype: typle
        """
        wg_private_base64, wg_public_base64 = self.generate_key_pair()

        node_public_bin = j.data.hash.hex2bin(node_public_key)
        node_public = VerifyKey(node_public_bin)
        box = SealedBox(node_public.to_curve25519_public_key())

        wg_private_encrypted = box.encrypt(wg_private_base64)
        wg_private_encrypted_hex = j.data.hash.bin2hex(wg_private_encrypted)

        return (wg_private_base64.decode(), wg_private_encrypted_hex.decode(),
                wg_public_base64.decode())
Beispiel #19
0
    def serialise(self, signing_key: SigningKey):
        # Create buffer
        buffer = BytesIO()

        # Write magic number
        buffer.write(Frame.MAGIC_NUMBER)

        # Write the destination key
        buffer.write(self.destination.serialise().read())

        # Write the origin key
        buffer.write(self.origin.serialise().read())

        # Write the via field
        buffer.write(self.via.serialise().read())

        # Create a box to send the signed data in
        box = SealedBox(self.destination.public_key)

        # Sign the payload
        signed = signing_key.sign(self.payload.read())

        # Encrypt and write the data to the buffer
        buffer.write(box.encrypt(signed))

        # Rewind the buffer
        buffer.seek(0, 0)

        # Return the buffer
        return buffer
Beispiel #20
0
def encrypt_password(password, public_key):
    node_public_bin = j.data.hash.hex2bin(public_key)
    node_public = VerifyKey(node_public_bin)
    box = SealedBox(node_public.to_curve25519_public_key())

    pasword_encrypted = box.encrypt(password.encode())
    pasword_encrypted_hex = j.data.hash.bin2hex(pasword_encrypted)
    return pasword_encrypted_hex
Beispiel #21
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 #22
0
def encrypt_sealed_box(message, public_rec):
    message = message.encode('utf-8')
    public_rec = check_key(public_rec)
    public_rec = bytes.fromhex(public_rec)
    public_rec = PublicKey(public_key=public_rec)
    sealed_box = SealedBox(public_rec)
    encrypted = sealed_box.encrypt(message)
    return base64.b64encode(encrypted).decode('utf-8')
Beispiel #23
0
def encrypt(message, key, output):
    message_bytes = message.encode('ascii')
    with open(key, mode="rb") as key_file:
        key_bytes = key_file.read()
    with open(output, "wb") as output_file:
        pub_key = PublicKey(key_bytes)
        sealed_box = SealedBox(pub_key)
        output_file.write(sealed_box.encrypt(message_bytes))
 def upload_side_effect(encrypted_filename, encrypted_data, file_type):
     """Verify the encrypted file exists at this point"""
     # verify the upload was triggered with the expected encrypted filename and that file exists
     assert SealedBox(private_key).decrypt(
         encrypted_data) == file_contents
     assert encrypted_filename == expected_encrypted_filename
     assert file_type == 'sometype'
     return expected_encrypted_keypath
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)
def encrypt():
    decrypted_utf8 = read_file('decrypted.txt')
    decrypted_bin = bytes(decrypted_utf8, 'utf-8')
    public_key_bin = read_file('public_key.txt', True)
    public_key = PublicKey(public_key_bin)
    sealed_box = SealedBox(public_key)
    encrypted_bin = sealed_box.encrypt(decrypted_bin)
    write_file("encrypted.txt", encrypted_bin, True)
Beispiel #27
0
    def privateMessage(self, message, targetUsername, apiKey, prikey):
        #self, message, targetusername, apikey, prikey
        client_saved_at = str(time.time())
        sqlite.insertPM(self, self.username, targetUsername, self.username,
                        targetUsername, message, client_saved_at)
        data = sqlite.getOnline(self)
        for i in range(len(data["name"])):
            if (data["name"][i] == targetUsername):
                address = data["address"][i]
        url = "http://" + address + "/api/rx_privatemessage"
        loginserver_record = self.LoginServerRecord(apiKey)

        target_pubkey = str(sqlite.findOnline(self, str(targetUsername)))
        print(target_pubkey)
        pubkey = nacl.signing.VerifyKey(target_pubkey,
                                        encoder=nacl.encoding.HexEncoder)
        curvedrxpubkey = pubkey.to_curve25519_public_key()
        sealed_box = SealedBox(curvedrxpubkey)
        message = bytes(message, encoding='utf-8')
        encrypted = sealed_box.encrypt(message,
                                       encoder=nacl.encoding.HexEncoder)
        signed = bytes(loginserver_record + target_pubkey + targetUsername +
                       encrypted.decode('utf-8') + client_saved_at,
                       encoding='utf-8')
        signature = prikey.sign(signed, encoder=nacl.encoding.HexEncoder)
        headers = {
            'X-username': self.username,
            'X-apikey': apiKey,
            'Content-Type': 'application/json; charset=utf-8',
        }
        payload = {
            "loginserver_record": loginserver_record,
            "target_pubkey": target_pubkey,
            "target_username": targetUsername,
            "encrypted_message": encrypted.decode('utf-8'),
            "sender_created_at": client_saved_at,
            "signature": signature.signature.decode('utf-8')
        }
        payload_str = json.dumps(payload)
        json_payload = payload_str.encode("utf-8")
        try:
            req = urllib.request.Request(url,
                                         data=json_payload,
                                         headers=headers)
            response = urllib.request.urlopen(req)
            data = response.read()
            encoding = response.info().get_content_charset('utf-8')
            response.close()
        except urllib.error.HTTPError as error:
            print("$$$$$$$$$$$$$$$$$$")
            print(error.read())
            exit()
        print("##############33")
        print(data)
        print("#################")

        JSON_object = json.loads(str(data.decode(encoding)))
        print(JSON_object)
Beispiel #28
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 #29
0
def auth():
    auth_host = '10.50.8.128'
    #with open('private_key', 'rb') as f:
    #f.write('Hello\n')
    with open('private_key') as f:
        encoded_private_key = f.read()
    with open('public_key') as f:
        encoded_public_key = f.read()
    loaded_public_key = PublicKey(encoded_public_key,
                                  encoder=nacl.encoding.Base64Encoder)
    loaded_private_key = PrivateKey(encoded_private_key,
                                    encoder=nacl.encoding.Base64Encoder)
    # assert loaded_public_key.encode() == loaded_private_key.public_key.encode()
    #assert loaded_public_key.encode() == loaded_private_key.public_key.encode()
    print(loaded_public_key.encode())
    print(loaded_private_key.public_key.encode())
    private_key = loaded_private_key
    public_key = loaded_public_key

    # return 1

    # private_key = private_key_b64.decode('base64')
    # public_key = public_key_b64.decode('base64')

    # with open('public_key', 'rb') as f:
    #     f.write(encoded_public_key)
    # with open('x.py') as f: s = f.read()
    # # Generate Bob's private key, as we've done in the Box example
    # skbob = PrivateKey.generate()
    # pkbob = skbob.public_key
    #return private_key

    # Alice wishes to send a encrypted message to Bob,
    # but prefers the message to be untraceable
    #sealed_box = SealedBox(pkbob)
    sealed_box = SealedBox(private_key)

    # This is Alice's message
    message = b"Kill all kittens"

    # Encrypt the message, it will carry the ephemeral key public part
    # to let Bob decrypt it
    encrypted = sealed_box.encrypt(message)
    msg = base64.b64encode(encrypted)
    msg = encoded_public_key
    #data = {'name': 'jtest', 'ipaddr': '192.168.0.2' 'public_key': b'\x8e\x05{\xe2\xcby:\x0b\xeb\xe69\xac|\x96\xff\xa4\xdaE\x89^\xa7\xaf\x90\x83\x14)bP\x0c\n\x85l'}
    #data = {'msg': ''}
    data = {'msg': msg}
    print(data)
    #return 1
    #r = requests.post('https://stats.rchain.me:30443/auth', data = data)
    r = requests.post(f'https://{auth_host}:30443/auth', data=data)
    print(r)
    text = r.text
    content = r.content
    print(text)
    print(content)
Beispiel #30
0
def test_wrong_types():
    priv = PrivateKey.generate()

    check_type_error(("SealedBox must be created from a PublicKey"
                      " or a PrivateKey"), SealedBox, priv.encode())
    check_type_error(("SealedBox must be created from a PublicKey"
                      " or a PrivateKey"), SealedBox, priv.public_key.encode())
    with pytest.raises(TypeError):
        SealedBox(priv, priv.public_key)