# Encrypt

`POST /crypto/encrypt` · Core · Encryption

Encrypts up to 100 items with the project's key; the key never leaves the platform and you never choose one. Read the project's custody mode and `custodyEpoch` from GET /crypto/mode first, and send that `custodyEpoch`.

Send a `crypt` (lowercase letters, digits and hyphens, up to 64 characters), the unit you grant access on, and `items`, each a base64 `plaintext` of at most 64 KiB (1 MiB per call) with an optional `context` of up to 256 bytes. Returns `items`, one opaque, base64 `ciphertext` per item, in order. Decrypting needs the same `crypt` and `context`.

Requires the `crypto` encrypt permission on the crypt (project editors and admins by default), held through project membership: an org role alone does not count. A personal access token scoped to `crypto` crypts encrypts only under those crypts. A call that ran answers 200, even if some or all of its items failed.

This API serves platform-managed keys. A project whose key is held in your own cloud KMS gets 409 `K9O_ZK_STORE_FLOW_REQUIRED` for the whole call: use the SDK's client-side `kibo.encrypt` / `kibo.decrypt`, which call your KMS directly. Under self-deployed hold-your-own-key custody the key operations run in your HSM, so calls take longer, and an HSM that cannot be reached fails the whole call.

Ciphertext from this API cannot be opened by client-side Kibo or by an extension's `k9o.kibo.encrypt`, and theirs cannot be opened here.

Erasure: this ciphertext becomes unreadable everywhere when the project's key is zeroized or the project is purged. It is not covered by per-subject erasure, because the platform does not know whose data you encrypted.

## Parameters

| Name | In | Required | Description |
|---|---|---|---|
| `projectSlug` | path | yes | The project's slug: the path segment after `@`. It is unique within the org. Example: `"storefront"`. |

## Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `crypt` | string | yes | The crypt: the authorisation unit, bound into the ciphertext |
| `custodyEpoch` | string | yes | Required. The custody epoch from GET /crypto/mode, opaque. If the project's key custody has changed since, the call is refused (409 K9O_ZK_STORE_FLOW_REQUIRED) with the current mode, route and epoch |
| `items` | array of object | yes | The values to process, 1 to 100. Each is handled on its own, and the answer has one entry per item, in the same order. |
| `items.[]plaintext` | string | yes | The data, standard base64 |
| `items.[]context` | string | no | Optional caller-chosen context, at most 256 bytes; the same value is needed to decrypt |

```json
{
  "crypt": "customer-pii",
  "custodyEpoch": "42",
  "items": [
    {
      "plaintext": "YWxpY2VAZXhhbXBsZS5jb20=",
      "context": "user:usr_8f2k"
    }
  ]
}
```

## Responses

- **200**: Success

| Field | Type | Required | Description |
|---|---|---|---|
| `data` | object | yes | The result for each item. |
| `data.items` | array of object | yes | One entry per request item, in order. The call is 200 whether some or all items failed. |
| _one of_ | | |  |
| `data.items.[]ciphertext` | string | yes | standard base64 |
| _or_ | | |  |
| `data.items.[]code` | string | yes | K9O_ENVELOPE_INTEGRITY_FAILURE (cannot be opened; no further detail) or K9O_SEALED_UNDER_RETIRED_KEY (rewrap it) |
| `data.items.[]message` | string | yes | A readable explanation of `code`, for logs. Branch on `code`, not on this text. |
| `data.items.[]context` | object | yes | Empty, except resealableUntil on K9O_SEALED_UNDER_RETIRED_KEY |
| `meta` | object | yes |  |


## Errors

| HTTP | Code | When |
|---|---|---|
| 400 | `K9O_INVALID_FIELD_VALUE` | The body is not exactly { crypt, items }, crypt does not match ^[a-z0-9-]{1,64}$, items is not 1 to 100 objects of the expected field and an optional context, a value is not standard base64, or a context is over 256 bytes. |
| 400 | `K9O_INVALID_REQUEST_SHAPE` | The body does not match the schema; context.detail names each field. A missing or malformed `custodyEpoch` (^[A-Za-z0-9_.:-]{1,128}$) is refused here. |
| 401 | `K9O_UNAUTHENTICATED` | The caller is not authenticated. |
| 403 | `K9O_ACCESS_DENIED` | The caller is not an accepted member of this project (an org role alone does not count). |
| 403 | `K9O_IAM_POLICY_DENIED` | The caller's policy does not allow this crypto action on this crypt. |
| 403 | `K9O_EXTENSION_PERMISSION_DENIED` | Extensions use k9o.kibo.encrypt and k9o.kibo.decrypt instead. |
| 403 | `K9O_RBAC_DENY` | End users cannot call this API. |
| 410 | `K9O_PROJECT_ZEROIZED` | The project's key has been zeroized; nothing can be sealed or opened under it. |
| 413 | `K9O_PAYLOAD_TOO_LARGE` | An item is over 64 KiB, or the call is over 1 MiB (context.scope says which). |
| 429 | `K9O_RATE_LIMITED` | The project is over its rate of crypto items; retry after the Retry-After seconds. |
| 503 | `K9O_KEY_SERVICE_UNAVAILABLE` | The key service could not complete the call. Nothing was returned; retry. |
| 503 | `K9O_BYOK_KEY_UNREACHABLE` | The project's cloud KMS key cannot be reached. |
| 503 | `K9O_HYOK_CLUSTER_UNREACHABLE` | No host of the project's HSM cluster can be reached. |
| 403 | `K9O_PAT_COLLECTION_NOT_PERMITTED` | The personal access token is scoped to other `crypto` crypts. |
| 409 | `K9O_ZK_STORE_FLOW_REQUIRED` | Refused before any key work, for the whole call, in two cases:

1. The project's key is held in your own cloud KMS: this API serves platform-managed keys only, so use the SDK's client-side kibo.encrypt / kibo.decrypt, which call your KMS directly.
2. `custodyEpoch` is not the project's current custody epoch: custody changed since you read it.

The response `context` is:

```
{ route: "client" \| "server", custodyMode?: "PLATFORM_MANAGED" \| "SKR" \| "BYOK" \| "HYOK", epoch?: the current custody epoch }
```

custodyMode is left out when it is not known; epoch is set when the refusal is a stale epoch. recommendation: { action }. |
| 404 | `K9O_CRYPT_NOT_FOUND` | The crypt is not registered in this project: create it first with POST /crypto/crypts. |
| 409 | `K9O_CRYPT_RETIRED` | The crypt is retired. Decrypt and rewrap still work; encrypt doesn't. |
| 409 | `K9O_BYOK_REGION_MISMATCH` | The project's customer-managed key does not cover the region this request is served in, so nothing was sealed; the key is never replaced with a platform key. |

## Code samples

### cURL

```bash
curl -X POST 'https://<org>.api-<region>.k9o.io/@storefront/crypto/encrypt' \
  -H 'Authorization: Bearer $K9O_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
  "crypt": "customer-pii",
  "custodyEpoch": "42",
  "items": [
    {
      "plaintext": "YWxpY2VAZXhhbXBsZS5jb20=",
      "context": "user:usr_8f2k"
    }
  ]
}'
```

### fetch

```javascript
const res = await fetch('https://<org>.api-<region>.k9o.io/@storefront/crypto/encrypt', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.K9O_TOKEN}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
  "crypt": "customer-pii",
  "custodyEpoch": "42",
  "items": [
    {
      "plaintext": "YWxpY2VAZXhhbXBsZS5jb20=",
      "context": "user:usr_8f2k"
    }
  ]
}),
});
const { data, meta } = await res.json();
```

### k9o CLI

```bash
k9o crypto encrypt --crypt <crypt>
```

### @k9o/core

```typescript
// const k9o = new K9o({ orgSlug: 'playground', projectSlug: 'storefront', apiKey: 'k9o_…' })
const { data } = await k9o.crypto.encrypt({
  crypt: 'customer-pii',
  custodyEpoch: '42',
  items: [{
    plaintext: 'YWxpY2VAZXhhbXBsZS5jb20=',
    context: 'user:usr_8f2k'
  }]
})
```

### k9o

```python
# k9o = create_client(org_slug="playground", project_slug="storefront", api_key="k9o_…")
response = k9o.crypto.encrypt({
    "crypt": "customer-pii",
    "custodyEpoch": "42",
    "items": [{
        "plaintext": "YWxpY2VAZXhhbXBsZS5jb20=",
        "context": "user:usr_8f2k"
    }]
})
```

### sdk-go

```go
// ctx := context.Background()
// client, _ := k9o.NewClient(k9o.ClientOpts{OrgSlug: "playground", ProjectSlug: "storefront", APIKey: "k9o_…"})
data, _, kerr := client.Crypto.Encrypt(ctx, map[string]any{"crypt": "customer-pii", "custodyEpoch": "42", "items": []any{map[string]any{"plaintext": "YWxpY2VAZXhhbXBsZS5jb20=", "context": "user:usr_8f2k"}}})
```

### k9o

```rust
// let k9o = Client::new(ClientOpts { org_slug: "playground".into(), project_slug: "storefront".into(), api_key: "k9o_…".into() })?;
let resp = k9o.crypto.encrypt(json!({"crypt": "customer-pii", "custodyEpoch": "42", "items": [json!({"plaintext": "YWxpY2VAZXhhbXBsZS5jb20=", "context": "user:usr_8f2k"})]})).await?
```

### dev.k9o:core

```java
// K9o k9o = K9o.createClient(K9o.Opts.builder().orgSlug("playground").projectSlug("storefront").apiKey("k9o_…").build());
var response = k9o.crypto().encrypt(Map.of("crypt", "customer-pii", "custodyEpoch", "42", "items", List.of(Map.of("plaintext", "YWxpY2VAZXhhbXBsZS5jb20=", "context", "user:usr_8f2k"))))
```

### K9o.Core

```c#
// var k9o = K9oClient.Create(new K9oOptions { OrgSlug = "playground", ProjectSlug = "storefront", ApiKey = "k9o_…" });
var response = await k9o.Crypto.EncryptAsync(new Dictionary<string, object> { ["crypt"] = "customer-pii", ["custodyEpoch"] = "42", ["items"] = new object[] { new Dictionary<string, object> { ["plaintext"] = "YWxpY2VAZXhhbXBsZS5jb20=", ["context"] = "user:usr_8f2k" } } })
```

### k9o

```ruby
# k9o = K9o.create_client(org_slug: "playground", project_slug: "storefront", api_key: "k9o_…")
response = k9o.crypto.encrypt({ crypt: "customer-pii", custodyEpoch: "42", items: [{ plaintext: "YWxpY2VAZXhhbXBsZS5jb20=", context: "user:usr_8f2k" }] })
```

### k9o/sdk

```php
// $k9o = K9oClient::create(['org_slug' => 'playground', 'project_slug' => 'storefront', 'api_key' => 'k9o_…']);
$response = $k9o->crypto->encrypt(['crypt' => 'customer-pii', 'custodyEpoch' => '42', 'items' => [['plaintext' => 'YWxpY2VAZXhhbXBsZS5jb20=', 'context' => 'user:usr_8f2k']]])
```


Canonical page: https://docs.kilimanjaro.dev/api-playground/core/encrypt
