# Session less usage of the API key with local decryption

# Preamble

Psono allows the access of simple secrets without the need to create sessions, handling renewal of sessions and so on. As a drawback, data exchanged this way is not protected by Psono's additional transport encryption layer. We assume at this point that you did create a restricted API key.

# Example with python

Requirements:

requests
pynacl

The script could look like this:

import requests
import json
import nacl.encoding
import nacl.secret

# Replace the values of the variables below with the details of your restricted API key:
api_key_id = '74...f1'
api_key_private_key = 'e6...7e'
api_key_secret_key = '1a...1c'
server_url = 'https:/example.com/server'
server_public_key = '02...0b'
server_signature = '4c...d1'


SSL_VERIFY = True


def api_request(method, endpoint, data = None):

    headers = {'content-type': 'application/json'}

    r = requests.request(method, server_url + endpoint, data=data, headers=headers, verify=SSL_VERIFY)

    return r.json()

def api_read_secret(secret_id):

    method = 'POST'
    endpoint = '/api-key-access/secret/'

    data = json.dumps({
        'api_key_id': api_key_id,
        'secret_id': secret_id,
    })

    encrypted_secret = api_request(method, endpoint, data)

    # decrypt step 1: Decryption of the encryption key
    crypto_box = nacl.secret.SecretBox(api_key_secret_key, encoder=nacl.encoding.HexEncoder)
    encryption_key = crypto_box.decrypt(nacl.encoding.HexEncoder.decode(encrypted_secret['secret_key']),
                                        nacl.encoding.HexEncoder.decode(encrypted_secret['secret_key_nonce']))

    # decrypt step 2: Decryption of the secret
    crypto_box = nacl.secret.SecretBox(encryption_key, encoder=nacl.encoding.HexEncoder)
    decrypted_secret = crypto_box.decrypt(nacl.encoding.HexEncoder.decode(encrypted_secret['data']),
                                          nacl.encoding.HexEncoder.decode(encrypted_secret['data_nonce']))

    return json.loads(decrypted_secret)

def main():

    secret_id = 'c81d0cff-65f9-4f81-9815-dbe2850331c9'

    decrypted_secret = api_read_secret(secret_id)

    print(decrypted_secret)


if __name__ == '__main__':
    main()