---
title: "Rotate the encryption key"
description: "Replace TOKEN_ENCRYPTION_KEY without losing stored secrets: add the new key beside the old one, re-encrypt, verify, and only then retire the old key."
---

`TOKEN_ENCRYPTION_KEY` encrypts every secret TRUSTIVAN has to hand back to a
third party: linked provider tokens, webhook signing secrets, single sign-on
client secrets, TOTP seeds, stored registry, git, cloud and Kubernetes
credentials, and notification destination secrets. This page is the procedure
for replacing it.

<Warning>
Never replace the value on its own. A process started with a new key and
nothing else treats every stored secret as version 1 ciphertext and tries to
open it with the new key. Nothing fails at startup. Every integration fails at
its first read. If that has happened, put the old value back and restart.
Existing rows were not overwritten. Anything stored while the wrong key was
live was sealed under it and has to be entered again.
</Warning>

## How rotation works

Each ciphertext is stored with the **version** of the key that sealed it, in
its own column. Decryption looks up the key for the version the row names;
encryption always uses the current one. So rotation is four states, and only
the last can lose data:

| State | Configuration | What works |
|---|---|---|
| Before | One key, version 1 | Everything |
| New key added | New key current, old key retained | New writes use the new key; old rows still open |
| Re-encrypted | The same, after `reencrypt apply` | Every row is on the new key and bound to its record; the old key is unused |
| Old key retired | New key only | Everything, provided the previous state was really reached |

Three variables carry it:

| Variable | Default | Purpose |
|---|---|---|
| `TOKEN_ENCRYPTION_KEY` | unset | The current key. 64 hex characters |
| `TOKEN_ENCRYPTION_KEY_VERSION` | `1` | The version new ciphertext is stamped with. An integer, 1 or greater |
| `TOKEN_ENCRYPTION_KEYS_PREVIOUS` | empty | Retired keys the process may still decrypt with, as comma-separated `version:hexkey` pairs |

A deployment that has never rotated sets only the first, and stays on version 1
with no change in behaviour.

## Before you start

- **Have the current key somewhere other than the running deployment.** You are
  about to move it into a second variable, and a typo there is recoverable only
  if you still have the original.
- **Take a database backup.** See
  [Backup and recovery](/deployment/backup-and-recovery).
- **Know how your deployment passes variables.** The production Compose file
  passes `TOKEN_ENCRYPTION_KEY_VERSION` and `TOKEN_ENCRYPTION_KEYS_PREVIOUS` to
  `api`, `worker` and `reencrypt` from the environment file. Before 2026-10-13
  it did not, and an override file was needed; see
  [Production Compose](/installation/production-compose#which-variables-reach-the-containers).
- **Rehearse on a restored copy.** The keyring and the sweep are covered by the
  repository's automated tests. The project's own limitation notes record that
  the procedure has not yet been exercised against a live deployment, so run it
  once against a restore of your database before you run it against the real
  one.

## Procedure

<Steps>
  <Step title="Generate the new key">
    ```bash
    openssl rand -hex 32
    ```

    Store it in your secret manager before you use it.
  </Step>

  <Step title="Add it as the current key and keep the old one">
    On **every** backend process (each API replica, each worker, and wherever
    you run `reencrypt`), set all three variables. For a first rotation, from
    version 1 to version 2:

    ```bash
    TOKEN_ENCRYPTION_KEY=<the new 64-hex key>
    TOKEN_ENCRYPTION_KEY_VERSION=2
    TOKEN_ENCRYPTION_KEYS_PREVIOUS=1:<the old 64-hex key>
    ```

    Then restart them. New writes now use version 2 and old rows still open.
    Nothing is broken, and nothing is finished.

    Workers need the same values as the API: a worker opens stored credentials
    to pull private images and clone private repositories.
  </Step>

  <Step title="Confirm the processes started">
    Startup refuses a keyring that would lose data, so a process that is
    running has a complete one. It exits with a named error when:

    - `TOKEN_ENCRYPTION_KEY_VERSION` is less than 1;
    - the version is above 1 and any version below it is missing from
      `TOKEN_ENCRYPTION_KEYS_PREVIOUS`;
    - `TOKEN_ENCRYPTION_KEYS_PREVIOUS` contains the current version;
    - an entry is not `version:hexkey`, names a version twice, is not hex, or
      does not decode to 32 bytes.

    ```bash
    curl -s http://localhost:8080/ready
    ```
  </Step>

  <Step title="See what is still on the old key">
    Run [`reencrypt report`](/cli-reference/reencrypt) as the schema owner, the
    same role `migrate` uses:

    ```bash
    docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env \
      run --rm reencrypt report
    ```

    Rows marked `<- not yet re-encrypted` are the work.
  </Step>

  <Step title="Dry-run, then apply">
    ```bash
    docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env \
      run --rm reencrypt plan
    docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env \
      run --rm reencrypt apply
    ```

    `plan` writes nothing. It proves the old key opens the rows and the new one
    seals them. An `UNREADABLE` count above zero usually means a key is missing
    from `TOKEN_ENCRYPTION_KEYS_PREVIOUS`; fix that before `apply`. The
    [command reference](/cli-reference/reencrypt#reading-the-output) lists the
    other causes.

    `apply` can run while the deployment serves traffic. It works in batches of
    500 rows, updates the ciphertext and its version in one statement, and
    leaves alone any row another writer has already moved. If it is
    interrupted, run it again.
  </Step>

  <Step title="Verify">
    ```bash
    docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env \
      run --rm reencrypt report
    ```

    You are done with the sweep when the last line reads:

    ```text
    every row is on the current key: previous keys can now be retired.
    ```
  </Step>

  <Step title="Retire the old key">
    Remove the old entry from `TOKEN_ENCRYPTION_KEYS_PREVIOUS` and restart.
    Leave `TOKEN_ENCRYPTION_KEY_VERSION` at its new value. Keep the retired key
    in your secret manager for as long as you keep database backups taken
    before the sweep: a restore of one of those brings back rows only that key
    can open.
  </Step>
</Steps>

There is no deadline between adding the new key and retiring the old one. A
deployment can run with a previous key indefinitely. What it must not do is
drop that key on the strength of "we rotated months ago" without a clean
`report`.

## Row binding

A ciphertext is sealed to the row that holds it. The organization id (where the
table has one), the row's id and the secret's purpose are passed to AES-GCM as
associated data, so they are authenticated without being stored. A value copied
from one row into another, in the same column or a different organization,
fails to open exactly as a tampered one does. Bound ciphertext starts with
`v2:`.

Ciphertext written before this existed has no binding and no prefix. It still
opens, and `reencrypt apply` rewrites it in the bound form whether or not you
are rotating a key: a row on the current key in the old format is work for the
sweep too. `report` counts those rows in its `UNBOUND` column.

**What stays open until you close it.** While the old format is accepted, an
old-format value (from before the sweep, or from a backup taken before it) can
still be copied between rows of the same column. Setting
`SECRETS_REQUIRE_BOUND=true` on every backend process makes them refuse
old-format ciphertext. Do that only when `report` ends with:

```text
every row is bound to its record: SECRETS_REQUIRE_BOUND can be switched on.
```

Three things to know before you set it:

- A row still in the old format stops opening. With the switch on, `apply`
  counts such a row as `UNREADABLE` and does not upgrade it, because upgrading
  it would turn a copied value into a valid one.
- Restoring a backup taken before the sweep brings old-format rows back. Switch
  it off, run `apply`, check `report`, switch it on again.
- `report` does not count queued notifications and mail. Those rows are sealed
  to their own id from the moment this version is running, and the ones queued
  earlier are delivered or abandoned within the retry schedule. A message
  queued before the upgrade and still pending when you set the switch is failed
  permanently, so leave a day between upgrading and switching it on.

Unlike the two rotation variables, `SECRETS_REQUIRE_BOUND` is not passed by the
production Compose file at this release. Add it with an override file, as
[Production Compose](/installation/production-compose#which-variables-reach-the-containers) shows.

## What else changes with the key

Two keys are derived from the **current** `TOKEN_ENCRYPTION_KEY` and are not
versioned. They change the moment the new key becomes current, whatever the
sweep does:

| Derived key | What you will see |
|---|---|
| Pagination cursor signing key | Cursors issued before the restart stop verifying. A client part-way through a paginated listing starts again from the first page |
| Secret-finding salt | A secret finding identifies a leaked value by a salted digest, and that digest is part of the finding's identity. After the rotation the same leak produces a different digest, so the next scan reports it as a new finding and resolves the old one. Triage state on the old finding does not carry over |

Plan the rotation with the second one in mind if your teams have triaged a
large number of secret findings.

`JWT_SECRET` is a separate secret with its own two-step rotation. See
[Environment variables](/configuration/environment#required).

## What this does not do

- **No automatic or scheduled rotation.** Every step above is something an
  operator runs.
- **This key is not the only layer.** Organization secrets are sealed under
  per-organization data keys that a KMS (AWS KMS, Cloud KMS, Vault Transit)
  can wrap instead of this key; see
  [Envelope encryption](/deployment/envelope-encryption).
- **No recovery of a lost key.** Rotation lets you replace a key you still
  hold. Ciphertext sealed under a key nobody has is not recoverable, and each
  affected integration has to be reconnected by the customer.

## Related

- [`reencrypt`](/cli-reference/reencrypt): the command's subcommands, output
  and exit status.
- [Credentials](/security/credentials): which secrets are encrypted and which
  are only hashed.
- [Upgrades](/deployment/upgrades): restarting processes in the right order.
