# Python

_Encrypt data server-side, invoke Functions, Enclaves and proxy requests through Relay._

> Encrypting/Decrypting data with our backend SDKs may expose you to greater
>   compliance burden because your server needs to handle plaintext data. Instead,
>   we recommend using [Relay](/relay) or our [Client-Side SDKs](/sdks) to encrypt
>   data.

## Getting started

### Install the SDK

Our Python SDK is distributed via [pypi](https://pypi.org/project/evervault/), and can be installed using `pip`.

```bash
pip install evervault
```

### Initialize the SDK

The SDK needs to be initialized with an App's ID and API key. If you don't have one yet, you can get one by creating an App in the [Evervault Dashboard](https://app.evervault.com).

```python
import evervault
evervault.init("<APP_ID>", "<API_KEY>")
```

### Encrypt a string

Now that the SDK is initialized, we can encrypt a string.

```python
encrypted = evervault.encrypt("Hello, world!")
```

## Reference

### init

Initializes the SDK with your API Key and App ID.

```python
import evervault

evervault.init(
    # Your App's ID
    app_id="<APP_ID>"
    # Your App's API key
    api_key="<API_KEY>",
)
```

**Parameters**

- `app_id` `String` _(required)_ — Your Evervault App's ID.
- `api_key` `String` _(required)_ — Your Evervault App's API Key.

### encrypt

Encrypts data using [Evervault Encryption](/developers/evervault-encryption). To encrypt a string using the Python SDK, simply pass a `str` or a `dict`, to encrypt a file, pass a `bytes` or `bytearray`. The encrypted data can be stored in your database or file storage as normal. Evervault Strings can be used across all of our products. Evervault File Encryption is currently in Beta, and files can only be decrypted with [Relay](/relay).

```python
import evervault
evervault.init(app_id="<APP_ID>", api_key="<API_KEY>")

## encrypt a string
encrypted = evervault.encrypt("Hello, world!")

## encrypt a file
with open("<input-filename>", mode="rb") as plaintext_file:
  contents = plaintext_file.read()
  encrypted_contents = evervault.encrypt(contents)
  with open("<output-filename>", "wb") as encrypted_file:
    encrypted_file.write(encrypted_contents)
```

**Parameters**

- `data` `str | dict | bytes | bytearray` _(required)_ — The data to encrypt.

### decrypt

Decrypts the data previously encrypted with the `encrypt()` function or through [Relay](/relay). An API key with the `decrypt` permission must be used to perform this operation.

```python
import evervault
evervault.init(app_id="<APP_ID>", api_key="<API_KEY>")
encrypted = evervault.encrypt("Hello, world!")
decrypted = evervault.decrypt(encrypted)
```

**Parameters**

- `data` `str | list | dict | bytes | bytearray` _(required)_ — The data to decrypt.

> **PCI Compliance**
>
> Decrypting data with our backend SDKs is not available if you are part of the PCI or HIPAA compliance use cases. Instead you can:
>
> - Use [Relay](/relay) to decrypt data before it reaches third-party services.
> - Use [Functions](/functions) or [Enclaves](/enclaves) to process encrypted data.

### run

Lets you invoke an [Evervault Function](/functions) with a given payload.

```python
import evervault
evervault.init(app_id="<APP_ID>", api_key="<API_KEY>")

result = evervault.run("hello-function", {
  "name": "Claude Shannon",
  "ssn": "ev:encrypted_string"
})
```

**Parameters**

- `function_name` `str` _(required)_ — The name of the function to invoke.
- `payload` `dict` _(required)_ — The payload to pass to the function.
- `run_async` `bool` — Whether to run the Function asynchronously or not. Callback URL must be configured in the Evervault Dashboard to receive a webhook on Function completion. Asynchronous Function invocations must be enabled for your team by contacting support@evervault.com.

Successful Function runs will return a dictionary containing a Function Run ID and the result from your Function in the following format:

```json
{
  "id": "func_run_09413338da56",
  "status": "success",
  "result": {
    "message": "Hello from a Function! It seems you have 14 letters in your name",
    "name": "ev:RFVC:TTLHY04oVJlBuvPx:A7MeNriTKFES0Djl9uKaPvHCAn9PjSfOHu7tswXFCHF9:jwYKE13o3iQlr6Dn/DRk80XpNOGb:$"
  }
}
```

In the case of an asynchronous Function invocation the result will be in the following format:

```json
{
  "id": "func_run_09413338da56",
  "status": "scheduled"
}
```

### create_run_token

Creates a single use, time bound token (5 minutes) for invoking an [Evervault Function](/functions) with a given payload. Run Tokens can be used to invoke an Evervault Function client-side without providing a sensitive API Key.

```python
import evervault
evervault.init(app_id="<APP_ID>", api_key="<API_KEY>")

result = evervault.create_run_token(
    "hello-function",
    {
        "name": "Claude Shannon",
        "ssn": "ev:encrypted_string"
    }
)
```

**Parameters**

- `function_name` `str` _(required)_ — The name of the function to invoke.
- `data` `dict` — Payload that the token can be used with. If not provided, a run token will be created, and the payload will not be validated when the function is executed.

### create_client_side_decrypt_token

Client Side Decyrpt Tokens are versatile and short-lived tokens that frontend applications can utilise to decrypt data previously encrypted through Evervault. Client Side Decrypt Tokens are restricted to specific payloads. By default, a Client Side Decrypt Token will live for 5 minutes into the future. The maximum time to live of the token is 10 minutes into the future.

```python
from datetime import datetime, timedelta
import evervault

evervault.init(app_id="<APP_ID>", api_key="<API_KEY>")
encrypted = evervault.encrypt("Hello, world!")
now = datetime.now()
time_in_five_minutes = now + timedelta(minutes=5)

token = evervault.create_client_side_decrypt_token(encrypted_data, time_in_five_minutes)
```

**Parameters**

- `payload` `str | list | dict | bytes | bytearray` _(required)_ — The data to decrypt.
- `expiry` `datetime` — The time the token will expire. Defaults to 5 minutes in the future.

When you create a Run Token, the SDK will return a JSON object containing your token.

```json
{
  "token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsInZlciI6IjAuMCJ9.eyJhcHBVdWlkIjoiYXBwX2RmZGE3MmUwMTZiMCIsImZ1bmN0aW9uTmFtZSI6ImhlbGxvLWNhZ2UtdGFsbC13YWxscy10cmF2ZWwiLCJydW5JZCI6IjRiMjhmMzNlLWU3NjYtNDI2OC1iNmY2LTUyYzZkM2VmMGQzYyIsImV4cCI6MTY2Nzg3Njc2Nn0.gCiFw7UJ8gjZfeXNEaqX4H1Y9HBX9avjioZ4yDU8PTtmGT4QTzVOhnDV46v_yyXLxpO1BgzoBRpYbLciiW1_QXSLmx6cCuJy4vHUZwssHT13vB7AXIl_88Ab5R7w9vpOQIDoCjhPVWJsolwUiiGh_5yE4wGv6WPTIfSv249_hpJLMz3AAffXUckiLPxFporY73KXtTANQH_zniivB91KdBnyGhle7gTs1EXWLqpdMIrqOz9cmoXU31DGd-AgeMzM082s_XtdCFq7FNLLtg6Nx8Mx8Bjl0cKV41R-jbTpHSXxutLX-PSDmWn5wSqDhlQoEWdTLsoS6xp7qhZ2urYyYg"
}
```

Run Tokens can then be used to authenticate Function runs from the client-side.

```javascript
fetch("https://api.evervault.com/functions/[function-name]/runs", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `RunToken [run-token]`,
  },
  body: JSON.stringify({
    payload: {
      ssn: "encrypted_string",
    },
  }),
});
```

### enable_outbound_relay

> This should only be used when you need to configure third party SDKs with
>   Relay. All other use cases should call Relay with a HTTP Client.

Configures your application to proxy HTTP requests using [Relay](/relay) based on the configuration created in the Evervault dashboard. See [Relay](/relay) to learn more.

Asynchronous HTTP requests are supported with [aiohttp](https://docs.aiohttp.org/). Pass in a [aiohttp.ClientSession](https://docs.aiohttp.org/en/stable/client_reference.html) to enable them for that session.

```python
evervault.enable_outbound_relay()
```

**Parameters**

- `decryption_domains` `str[]` — Requests sent to any of the domains listed will be proxied through Relay. This will override the configuration created using the Evervault dashboard.
- `debug_requests` `bool` — Output request domains and whether they were sent through Relay.
- `client_session` `aiohttp.ClientSession` — The [aiohttp](https://docs.aiohttp.org/) client session to enable relay on. Requires Python 3.11+.

### attestable_encalve_session

Returns a `Requests` session with will attest your Enclave during the [TLS handshake](/enclaves#attestationintls).

By default the client will attest the Enclave using the attestation document but will not make any assertions about the values of the PCRs. The attestation can be further scoped to the software running in your enclave by passing a dict mapping Enclave names to their corresponding PCRs.

```python
# assert that the Enclave was signed with a known cert
attested_session = evervault.attestable_enclave_session({
  'my-enclave': { 'pcr_8': '606e2c1cae65ee569799803388d2ca285ad5c325f9d7c0d4a38b3aa30bd729ba96a9a13e64577a622a0a1f050f722123' }
})

attested_session.post(
  'https://my-enclave.my-app.enclave.evervault.com',
  data=sensitive_payload
)
```

**Parameters**

- `enclave_attestation_data` — Optional constraints to assert that the PCRs present in the Enclave's attestation doc match the expected values. This can be either a single dict, or a list of dicts to allow roll-over between different sets of PCRs.You can also provide a callback function which returns a set of PCRs for an Enclave. This can make it easier to migrate your clients across Enclave deployments as the PCRs inevitably change.
  - `enclave_attestion_data.[enclaveName].pcr0` `str` — The PCR0 to use when attesting the given Enclave.
  - `enclave_attestion_data.[enclaveName].pcr1` `str` — The PCR1 to use when attesting the given Enclave.
  - `enclave_attestion_data.[enclaveName].pcr2` `str` — The PCR2 to use when attesting the given Enclave.
  - `enclave_attestion_data.[enclaveName].pcr8` `str` — The PCR8 to use when attesting the given Enclave.

#### Using the Evervault API as a PCR Provider

The Evervault API exposes an endpoint to retrieve the PCRs for all active deployments of an Enclave. This can be used to keep your Client in sync with your Enclave across deployments.

```python
import evervault
import requests
import json

evervault.init(app_id="app_1234", api_key="my_api_key")

def resolve_pcrs_from_evervault():
   resp = requests.get('https://api.evervault.com/enclaves/my-enclave/attestation', headers={'x-evervault-app-id': 'app-1234'})
   payload = json.loads(resp)

   #The API returns PCRs in camelCase, so we convert them to snake_case
   snake_case_pcrs = {"data": [{k.replace('pcr', 'pcr_'): v for k, v in pcr.items()} for pcr in payload["data"]]}
   return snake_case_pcrs["data"]

attested_session = evervault.attestable_enclave_session({
  'my-enclave': resolve_pcrs_from_evervault
})

attested_session.post('https://my-enclave.app-1234.enclave.evervault.com', headers = { 'api-key': 'my_api_key' })
```

