Skip to content

How to Move Vault-Encrypted Data to New Keys Safely

Re-encrypt Vault transit data under new keys without a mixed state: record the key per row, checkpoint each customer, size for big fields, verify in Python.

19 min read

About one coffee long. Hot or iced, your call.

Say you run a platform where security teams record what they find: vulnerabilities, pentest notes, the occasional screenshot of a password on a sticky note. That text is sensitive, so the app never holds an encryption key. It sends each finding to the transit engine in HashiCorp Vault, under that customer's own key, and stores the string that comes back. PostgreSQL fills up with values like vault:v1:4cr/PxBKio03S8m..., and for years nobody thinks about them again.

Then the Vault cluster gets a retirement date, and before it goes you have to re-encrypt Vault transit data under keys a new cluster holds. Maybe the company is changing clouds, maybe a token leaked, maybe the contract simply ended. The database copies across in an afternoon. The encrypted fields in it still open only for the old cluster.

It looks like a Friday-afternoon job: loop over the rows, decrypt on the old Vault, encrypt on the new one, update the row. In the lab below, that loop gets through seven customers. Then it meets customer c08, whose findings include a 900,000-byte report, comfortably under 1 MB, and the new Vault refuses it. The run dies with c08 half on each key.

Now look at the database. Every row still starts with vault:v1:, exactly as before the run, so nothing tells you which rows moved. Running the loop again would send rows it already re-encrypted back to the old Vault, which can't read them. Come Monday, a customer opens one finding fine and gets an error on the next, and nobody can say which rows to fix. That's the problem.

The way out is to treat this as a data migration that happens to call a crypto API, not the other way round. Make every row record which key holds it, commit per customer so a re-run skips finished work, size the job for your largest field, and prove the result with checks that never write plaintext anywhere.

I've done this for real: on a recent migration, a security company's Django service had about 300,000 encrypted fields under dozens of per-customer keys, and the GCP to AWS cutover guide tells that story. This tutorial is the version I'd want next time, built and broken on a laptop first.

In this tutorial, you'll run two Vault servers and PostgreSQL in Docker, break the naive loop, then build a resumable Python job against Vault's HTTP API. The post shows the code that matters; the full lab, plumbing included, is on GitHub in ShahidYousufBlogLabs. Tested with Vault 2.2.2, PostgreSQL 18.7, Python 3.14.8, psycopg 3.3.9 and requests 2.34.2.

What Re-Encrypting Vault Transit Data Involves#

Think of the transit engine as a locksmith who never hands out keys: you keep the locked box, the key stays in the shop. Moving shops means carrying every box back to the old locksmith to be opened, then to the new one to be locked again. The contents pass through your hands in between, so this tutorial is mostly bookkeeping and cleanup.

The label on each box won't help you sort them. In vault:v1:<base64>, the v1 is the key's version inside one Vault. It names no cluster and no key, and a fresh key on a fresh cluster also starts at version 1. That's why the naive loop leaves you blind, and why the steps below start by writing the answer down.

Prerequisites#

Step 1: Set Up Two Vaults and a Database#

The lab has an old Vault, a new Vault, PostgreSQL full of ciphertext, and a job container. Each customer has its own transit key, a common way to isolate tenants. Clone the lab and work from its folder:

git clone https://github.com/ShahidYousuf/ShahidYousufBlogLabs.git
cd ShahidYousufBlogLabs/reencrypt-vault-transit-data-python

The Compose file wires the four containers together:

docker-compose.yml
services:
  db:
    image: postgres:18.7
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: findings
    volumes:
      - ./schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -h localhost -U app -d findings"]
      interval: 1s
      timeout: 3s
      retries: 30

  old-vault:
    image: hashicorp/vault:2.2.2
    command: server -dev
    environment:
      VAULT_DEV_ROOT_TOKEN_ID: old-root
      VAULT_LOCAL_CONFIG: >-
        {"listener": [{"tcp": {"address": "0.0.0.0:8210", "tls_disable": true,
          "max_request_size": 67108864,
          "max_json_string_value_length": 33554432}}]}
    healthcheck:
      test: ["CMD-SHELL", "VAULT_ADDR=http://127.0.0.1:8200 vault status"]
      interval: 1s
      retries: 30

  new-vault:
    image: hashicorp/vault:2.2.2
    command: server
    volumes:
      - ./new-vault.hcl:/vault/config/new-vault.hcl:ro
      - new-vault-data:/vault/file
    healthcheck:
      # vault status exits 2 when sealed, 1 when unreachable.
      # Healthy here means "answering", sealed or not.
      test:
        - CMD-SHELL
        - VAULT_ADDR=http://127.0.0.1:8200 vault status; [ $$? -ne 1 ]
      interval: 1s
      retries: 30

  job:
    build: .
    environment:
      DATABASE_URL: postgresql://app:app@db:5432/findings
      OLD_VAULT_ADDR: http://old-vault:8210
      NEW_VAULT_ADDR: http://new-vault:8200
    volumes:
      - .:/lab
    working_dir: /lab
    depends_on:
      db:
        condition: service_healthy

volumes:
  new-vault-data:

The old Vault runs in dev mode, in memory. It stands in for an older cluster that accepted large values before Vault added JSON size limits, so it gets a second listener on port 8210 with those limits raised. The image's entrypoint loads VAULT_LOCAL_CONFIG even in dev mode. The new Vault is a normal server with file storage and default limits:

new-vault.hcl
storage "file" {
  path = "/vault/file"
}

listener "tcp" {
  address     = "0.0.0.0:8200"
  tls_disable = true
}

api_addr = "http://new-vault:8200"

Dev mode forgets everything

Restart the old Vault container and every ciphertext in the database becomes unreadable for good, which teaches Step 7's lesson six steps early. Both Vaults also run without TLS. Never copy either setup to a real environment.

The job container is Python 3.14 with psycopg and requests. The schema is two tables:

schema.sql
CREATE TABLE customers (
    id   text PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE findings (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id text NOT NULL REFERENCES customers,
    title       text NOT NULL,
    detail      text            -- vault:v1:... ciphertext, or NULL
);

CREATE INDEX findings_customer_id_idx ON findings (customer_id);

vaultlab.py is a small client for the transit API, using batch_input to handle many values per call. Its core is the Vault class. decrypt() returns plaintext still base64-encoded, on purpose (Step 5 explains why):

vaultlab.py (excerpt)
class Vault:
    def __init__(self, name: str, addr: str, token: str):
        self.name = name
        self.addr = addr
        self.http = requests.Session()
        self.http.headers["X-Vault-Token"] = token

    def call(self, method: str, path: str, body: dict | None = None) -> dict:
        r = self.http.request(
            method, f"{self.addr}/v1/{path}", json=body, timeout=300
        )
        if r.status_code >= 400:
            try:
                body = r.json()
            except ValueError:
                body = {"errors": [r.text.strip()]}
            # Batch calls report per-item errors inside batch_results instead.
            results = (body.get("data") or {}).get("batch_results") or []
            errors = body.get("errors") or sorted(
                {i["error"] for i in results if i.get("error")}
            )
            raise VaultError(f"{self.name} {r.status_code}: {errors}")
        return r.json() if r.content else {}

    def decrypt(self, key: str, ciphertexts: list[str]) -> list[str]:
        """Ciphertexts in, base64 plaintexts out (never decoded here)."""
        out = self.call(
            "POST",
            f"transit/decrypt/{key}",
            {"batch_input": [{"ciphertext": c} for c in ciphertexts]},
        )
        return [r["plaintext"] for r in out["data"]["batch_results"]]

    def encrypt(self, key: str, plaintexts_b64: list[str]) -> list[str]:
        out = self.call(
            "POST",
            f"transit/encrypt/{key}",
            {"batch_input": [{"plaintext": p} for p in plaintexts_b64]},
        )
        return [r["ciphertext"] for r in out["data"]["batch_results"]]

labvault.py is the admin script: it initializes the new Vault, creates one key per customer with the same names on both sides, turns on a file audit device, and issues scoped tokens (decrypt-only on the old Vault, encrypt and decrypt on the new).

seed.py plays the application: 30 customers, a few thousand findings, six large details (one of 20 MB), and a canary, a fake value you'll hunt for in Step 7:

seed.py (excerpt)
# customer -> sizes in bytes of its large details, stored side by side
LARGE = {
    "c08": [900_000],
    "c14": [1_500_000],
    "c22": [3_000_000, 20_000_000, 3_000_000],
    "c27": [1_200_000],
}
CANARY = "CANARY-" + secrets.token_hex(8)

Start everything and seed the data (add 2>/dev/null to hide Compose status lines). The healthchecks make --wait return only once both Vaults answer, so init doesn't race their startup:

docker compose up -d --wait db old-vault new-vault
docker compose build job
docker compose run --rm job python labvault.py init
docker compose run --rm job python labvault.py setup
docker compose run --rm job python seed.py
Output
new-vault initialized
new-vault sealed: False
old-vault: transit on, audit on, 30 keys, job token issued
new-vault: transit on, audit on, 30 keys, job token issued
seeded 30 customers, 3694 findings (6 with no detail)
canary: CANARY-be127f111d8a5da9  base64: Q0FOQVJZLWJlMTI3ZjExMWQ4YTVkYTk=

That's a real migration's starting point: 3,688 encrypted fields only the old Vault can read. Run docker compose logs new-vault | grep "Listener 1" and the new Vault reports max_json_string_value_length: "1048576". Remember that number.

Step 2: Watch the Naive Loop Fail#

Start with the loop most people write first:

rekey_naive.py
"""The obvious re-key: decrypt on the old Vault, encrypt on the new, update."""

from vaultlab import batches, connect, key_name, new_vault, old_vault

old, new = old_vault(), new_vault()

with connect(autocommit=True) as conn:
    customers = [
        r[0] for r in conn.execute("SELECT id FROM customers ORDER BY id")
    ]
    for cid in customers:
        rows = conn.execute(
            "SELECT id, detail FROM findings"
            " WHERE customer_id = %s AND detail IS NOT NULL ORDER BY id",
            (cid,),
        ).fetchall()
        for chunk in batches(rows, 50):
            plain = old.decrypt(key_name(cid), [detail for _, detail in chunk])
            cipher = new.encrypt(key_name(cid), plain)
            for (row_id, _), c in zip(chunk, cipher):
                conn.execute(
                    "UPDATE findings SET detail = %s WHERE id = %s",
                    (c, row_id),
                )
        print(f"{cid}: {len(rows)} rows re-encrypted")

Run it with docker compose run --rm job python rekey_naive.py. Seven customers go through, then:

Output
c07: 56 rows re-encrypted
Traceback (most recent call last):
  ...
vaultlab.VaultError: new-vault 500: ['JSON string value exceeds allowed length']

Count rows by prefix with SELECT left(detail, 9) AS prefix, count(*) FROM findings GROUP BY 1 and all 3,688 still start with vault:v1:, the same as before the run. The prefix can't tell you what moved. Neither can the app: read a moved row through the old Vault and you get this, which in production looks like corrupted data:

cipher: message authentication failed

The only way left is to ask each Vault about each row. When I decrypted c08's rows one at a time against both, 50 opened only on the new one and 65 only on the old. That's fine for 115 rows and hopeless for hundreds of thousands.

Step 3: Record Which Key Holds Each Row#

Write the answer down instead. A key_ref column stores the cluster and key name for every encrypted value. Reseed the lab with docker compose run --rm job python seed.py, then add the column. The same file keeps a copy of the old ciphertext in findings_before, standing in for the source database you're leaving; Step 6 verifies against it:

key_ref.sql
-- Which Vault cluster and which key can read each row.
ALTER TABLE findings ADD COLUMN IF NOT EXISTS key_ref text;

UPDATE findings
   SET key_ref = 'old-vault:findings-' || customer_id
 WHERE detail IS NOT NULL AND key_ref IS NULL;

CREATE INDEX IF NOT EXISTS findings_customer_key_ref_idx
    ON findings (customer_id, key_ref);

-- Stand-in for the source database you are leaving: Step 5 verifies against it.
DROP TABLE IF EXISTS findings_before;
CREATE TABLE findings_before AS SELECT id, customer_id, detail FROM findings;

Apply it with docker compose exec -T db psql -U app -d findings < key_ref.sql. Rows with no detail keep a NULL key_ref, so they never look like unfinished work. The application must also start writing key_ref and pick the Vault for each decrypt from it; schedule that change before the migration.

The job assumes writes are frozen while it runs. On the real migration the app's workers were scaled to zero for the window. The compare-and-set below stops the job from overwriting a newer row, but it can't stop the app from writing fresh ciphertext under the old key mid-run. If you can't pause writes, the FAQ covers the online approach.

The mover re-encrypts one batch and updates every row in one transaction with a compare-and-set:

mover.py
"""Move one batch of rows from the old key to the new key, safely."""

import psycopg

from vaultlab import Vault, key_name


def ref(cluster: str, customer_id: str) -> str:
    return f"{cluster}:{key_name(customer_id)}"


def move_batch(
    conn: psycopg.Connection,
    old: Vault,
    new: Vault,
    customer_id: str,
    rows: list[tuple[int, str]],
) -> tuple[int, int]:
    """Re-encrypt rows [(id, old ciphertext)]. Returns (moved, skipped)."""
    key = key_name(customer_id)
    plaintexts = old.decrypt(
        key, [detail for _, detail in rows]
    )  # base64, never decoded
    ciphertexts = new.encrypt(key, plaintexts)
    del plaintexts  # drops our reference; Python can't wipe it
    moved = 0
    with conn.transaction(), conn.cursor() as cur:
        for (row_id, old_detail), new_detail in zip(rows, ciphertexts):
            # Compare-and-set: only a row still holding exactly
            # this old ciphertext changes.
            cur.execute(
                "UPDATE findings SET detail = %s, key_ref = %s"
                " WHERE id = %s AND key_ref = %s AND detail = %s",
                (
                    new_detail,
                    ref("new-vault", customer_id),
                    row_id,
                    ref("old-vault", customer_id),
                    old_detail,
                ),
            )
            moved += cur.rowcount
    return moved, len(rows) - moved

The WHERE clause matches only a row that still has the old key_ref and exactly the ciphertext the job read. A row that already moved, or that the app changed since, matches nothing. Calling move_batch() twice on customer c01 with the same stale rows, as a job does when it crashes after a commit and retries, printed moved 122, skipped 0, then moved 0, skipped 122. I ran that from a short script, which is why c01 shows moved 0 in Step 4. A retry can waste work; it can't overwrite newer data with older.

Step 4: Checkpoint per Customer and Survive a Restart#

A restart should skip finished customers, retry failed ones, and never mark a customer done until a check proves it. A progress table records that:

progress.sql
CREATE TABLE IF NOT EXISTS rekey_progress (
    customer_id text PRIMARY KEY REFERENCES customers,
    status      text NOT NULL CHECK (status IN ('done', 'failed')),
    rows_moved  integer NOT NULL DEFAULT 0,
    error       text,
    updated_at  timestamptz NOT NULL DEFAULT now()
);

rekey.py runs every customer that isn't done:

rekey.py
"""Re-key every customer: resumable, checked per customer, with a breaker."""

import sys

from mover import move_batch, ref
from vaultlab import (
    VaultError,
    batches,
    connect,
    key_name,
    new_vault,
    old_vault,
)

MAX_CONSECUTIVE_FAILURES = 3


class CheckFailed(Exception):
    pass


def plan_batches(rows):
    """Up to 200 rows per Vault call."""
    return batches(rows, 200)


def check(conn, new, cid: str) -> int:
    """No rows left on the old key; the new key reads the biggest and 3 more."""
    left = conn.execute(
        "SELECT count(*) FROM findings WHERE customer_id = %s AND key_ref = %s",
        (cid, ref("old-vault", cid)),
    ).fetchone()[0]
    if left:
        raise CheckFailed(f"{left} rows still on the old key")
    sample = conn.execute(
        "(SELECT detail FROM findings WHERE key_ref = %(r)s"
        " ORDER BY length(detail) DESC LIMIT 1)"
        " UNION ALL"
        " (SELECT detail FROM findings WHERE key_ref = %(r)s"
        " ORDER BY random() LIMIT 3)",
        {"r": ref("new-vault", cid)},
    ).fetchall()
    for (detail,) in sample:
        new.decrypt(key_name(cid), [detail])  # raises VaultError if unreadable
    return len(sample)


def record(
    conn, cid: str, status: str, moved: int, error: str | None = None
) -> None:
    conn.execute(
        "INSERT INTO rekey_progress (customer_id, status, rows_moved, error)"
        " VALUES (%s, %s, %s, %s)"
        " ON CONFLICT (customer_id) DO UPDATE SET status = excluded.status,"
        " rows_moved = rekey_progress.rows_moved + excluded.rows_moved,"
        " error = excluded.error, updated_at = now()",
        (cid, status, moved, error),
    )
    conn.commit()


def main() -> None:
    old, new = old_vault(), new_vault()
    failures = 0
    with connect() as conn:
        todo = [
            r[0]
            for r in conn.execute(
                "SELECT c.id FROM customers c"
                " LEFT JOIN rekey_progress p ON p.customer_id = c.id"
                " WHERE p.status IS DISTINCT FROM 'done' ORDER BY c.id"
            )
        ]
        conn.commit()
        print(f"customers to go: {len(todo)}")
        for cid in todo:
            moved = skipped = 0
            try:
                rows = conn.execute(
                    "SELECT id, detail FROM findings"
                    " WHERE customer_id = %s AND key_ref = %s"
                    " ORDER BY id",
                    (cid, ref("old-vault", cid)),
                ).fetchall()
                conn.commit()
                for batch in plan_batches(rows):
                    m, s = move_batch(conn, old, new, cid, batch)
                    moved, skipped = moved + m, skipped + s
                sampled = check(conn, new, cid)
                conn.commit()
            except (VaultError, CheckFailed) as e:
                conn.rollback()
                record(conn, cid, "failed", moved, str(e))
                failures += 1
                print(f"{cid}: FAILED after moving {moved} rows: {e}")
                if failures >= MAX_CONSECUTIVE_FAILURES:
                    sys.exit(
                        f"circuit breaker: {failures} customers failed in a row,"
                        " stopping"
                    )
                continue
            except KeyboardInterrupt:
                conn.rollback()
                sys.exit(
                    f"interrupted in {cid}: not marked done,"
                    f" {moved} rows already moved"
                )
            record(conn, cid, "done", moved)
            failures = 0
            print(
                f"{cid}: moved {moved}, skipped {skipped},"
                f" checked {sampled} on the new key"
            )


if __name__ == "__main__":
    main()
flowchart LR A[Next pending customer] --> B[Batch: decrypt old, encrypt new, commit] B --> C{Customer check passes?} C -- yes --> D[Mark done] C -- no --> E[Count a failure] B -- Vault error --> E E --> F{3 in a row?} F -- yes --> G[Stop the run] F -- no --> A D --> A

Batches commit as they go, but only a passing check marks a customer done.

check() requires zero rows left on the old key, then decrypts the customer's largest value plus three random ones on the new Vault.

Apply progress.sql with docker compose exec -T db psql -U app -d findings < progress.sql, then run the job and interrupt it: docker compose run --rm job timeout -s INT 0.9 python rekey.py sends the same signal as Ctrl+C. The new Vault's size limit is still at its default, so expect some customers to fail; Step 5 fixes them. In my run, 19 customers finished, c08 and c14 were marked failed on the size limit while the run carried on, and the interrupt landed in c22, which stayed unmarked. Start it again without the timeout:

Output
customers to go: 11
c08: FAILED after moving 0 rows: new-vault 500: ['JSON string value ...']
c14: FAILED after moving 0 rows: new-vault 500: ['JSON string value ...']
c22: FAILED after moving 0 rows: new-vault 500: ['JSON string value ...']
circuit breaker: 3 customers failed in a row, stopping

The restart skipped the 19 finished customers. Then the breaker earned its keep: the three customers with big fields sort first, fail back to back for one reason, and the job stops. Three failures in a row isn't bad luck.

Rehearse in this order

On real data, rehearse one small customer, then the customer holding your largest field, then the full run. The second pass proves your limits before you've spent an hour on everyone else.

Step 5: Size the Job for Your Largest Field#

The failures come from the new Vault's TCP listener limits, here max_json_string_value_length (default 1 MiB). Vault reports the violation as a 500, so a retry-on-5xx loop must not retry it:

Defines the maximum allowed length in bytes for a single string value within a JSON payload.

Vault added these JSON limits with the fix for HCSEC-2025-24, so an older cluster may hold values its replacement refuses. Measure before changing anything:

docker compose exec db psql -U app -d findings -c "
  SELECT customer_id, id, length(detail) AS chars FROM findings
  ORDER BY length(detail) DESC NULLS LAST LIMIT 6"
Output
 customer_id |  id  |  chars   
-------------+------+----------
 c22         | 2661 | 26666713
 c22         | 2660 |  4000049
 c22         | 2662 |  4000049
 c14         | 1716 |  2000049
 c27         | 3347 |  1600049
 c08         |  851 |  1200049
(6 rows)

Transit sends plaintext as base64, which turns every 3 bytes into 4 characters (RFC 4648):

\[ \text{base64 length} = 4 \times \left\lceil \frac{n}{3} \right\rceil \]

So the 1 MiB limit admits about 786,432 plaintext bytes, and c08's 900,000 bytes travel as 1,200,000 characters. The 20 MB detail travels as 26,666,668. Raise the limit above that on the new Vault. In the repo the new listener is new-vault.step5.hcl; copy it over new-vault.hcl:

new-vault.step5.hcl
storage "file" {
  path = "/vault/file"
}

listener "tcp" {
  address     = "0.0.0.0:8200"
  tls_disable = true

  # Above the largest base64 value the job sends (26,666,668 characters).
  max_json_string_value_length = 33554432
}

api_addr = "http://new-vault:8200"

Restart the new Vault with docker compose restart new-vault, then unseal it with docker compose run --rm job python labvault.py unseal. The job never decodes the base64: it passes the old Vault's decrypt output straight into the new Vault's encrypt, and the 20 MB value came back byte for byte. Splitting a large field isn't an option, since the app decrypts it as one ciphertext.

Re-run rekey.py and you meet the next limit:

c22: FAILED after moving 0 rows: new-vault 413: ['http: request body too large']

c22 keeps its 20 MB detail beside two 3 MB ones, and a 200-row batch put all three in one request: more than 34.6 million characters against a max_request_size of 33,554,432. Raising it works too, as long as every batch stays under it; I'd rather cap batches by bytes and send big rows alone. Replace plan_batches() in rekey.py (and drop batches from its vaultlab import). The repo has the result as rekey.step5.py:

rekey.py (plan_batches)
MAX_ITEMS = 200
MAX_BYTES = 4 * 1024 * 1024


def plan_batches(rows):
    """Up to 200 rows or 4 MiB per Vault call; a bigger row goes alone."""
    batch, size = [], 0
    for row in rows:
        if batch and (
            len(batch) == MAX_ITEMS or size + len(row[1]) > MAX_BYTES
        ):
            yield batch
            batch, size = [], 0
        batch.append(row)
        size += len(row[1])
    if batch:
        yield batch

The largest request is now the 20 MB row alone, which fits the default max_request_size; raise that limit only if your largest field encodes above about 32 MB. One more run finishes the job: c22: moved 153, skipped 0, checked 4 on the new key, and the restart touched nothing else.

Step 6: Verify Without Storing Plaintext#

"Every customer passed its check" means every row decrypts on the new key, not that it decrypts to the right value. A bug that swapped two rows of one customer would pass, since both open with the same key.

verify.py checks the result against the source copy in findings_before. It counts rows per cluster (zero must remain on the old one, and the NULL rows show up on their own line), compares totals, then decrypts the 10 largest rows plus 100 random ones on both Vaults and compares them (up to 110 rows, since UNION drops duplicates).

It compares HMAC digests rather than the values themselves. That keeps 32 bytes per row in memory instead of a 26 MB value, and it lets you split the check when the old Vault is only reachable from the old environment: each side computes HMACs with a per-run key held in memory and never written down, and only digests cross. A plain SHA-256 won't do there, because a low-entropy value like a severity of High can be recovered by hashing every candidate:

verify.py
"""Prove the re-key without writing a single plaintext value anywhere."""

import base64
import hashlib
import hmac
import secrets
import sys

from mover import ref
from vaultlab import connect, key_name, new_vault, old_vault

# A random per-run key, held in memory and never written down.
CHECK_KEY = secrets.token_bytes(32)


def digest(plaintext_b64: str) -> bytes:
    return hmac.new(
        CHECK_KEY, base64.b64decode(plaintext_b64), hashlib.sha256
    ).digest()


old, new = old_vault(), new_vault()
with connect() as conn:
    counts = dict(
        conn.execute(
            "SELECT coalesce(split_part(key_ref, ':', 1), 'no detail'),"
            " count(*)"
            " FROM findings GROUP BY 1"
        ).fetchall()
    )
    before = conn.execute("SELECT count(*) FROM findings_before").fetchone()[0]
    print(
        f"rows: {counts}, total {sum(counts.values())}, before the run {before}"
    )

    # The 10 largest rows, which carry the size risk, plus 100 at random.
    sample = conn.execute(
        "(SELECT a.id, a.customer_id, b.detail, a.detail, a.key_ref"
        " FROM findings a"
        "  JOIN findings_before b USING (id) WHERE a.detail IS NOT NULL"
        "  ORDER BY length(a.detail) DESC LIMIT 10)"
        " UNION"
        " (SELECT a.id, a.customer_id, b.detail, a.detail, a.key_ref"
        " FROM findings a"
        "  JOIN findings_before b USING (id) WHERE a.detail IS NOT NULL"
        "  ORDER BY random() LIMIT 100)"
    ).fetchall()

mismatched = []
for row_id, cid, old_detail, new_detail, key_ref in sample:
    if key_ref != ref("new-vault", cid):
        mismatched.append(row_id)
        continue
    old_digest = digest(old.decrypt(key_name(cid), [old_detail])[0])
    new_digest = digest(new.decrypt(key_name(cid), [new_detail])[0])
    if not hmac.compare_digest(old_digest, new_digest):
        mismatched.append(row_id)

largest = max(len(s[3]) for s in sample)
print(
    f"sampled {len(sample)} rows (largest {largest:,} characters): "
    f"{len(sample) - len(mismatched)} match,"
    f" {len(mismatched)} differ {mismatched}"
)
ok = (
    counts.get("old-vault", 0) == 0
    and not mismatched
    and sum(counts.values()) == before
)
sys.exit(0 if ok else "verification FAILED")

The clean run reported 110 match, 0 differ. A check you've never seen fail proves little, so I swapped the ciphertexts of two large c22 rows with UPDATE findings f SET detail = o.detail FROM findings o WHERE (f.id, o.id) IN ((2660, 2662), (2662, 2660)); and ran it again:

Output
rows: {'no detail': 6, 'new-vault': 3688}, total 3694, before the run 3694
sampled 110 rows (largest 26,666,713 characters): 108 match, 2 differ [2660, 2662]
verification FAILED

Both swapped rows still decrypted fine, so rekey.py's own check would have passed them. The script exits non-zero, so a pipeline can gate on it.

Step 7: Clean Up Plaintext and Old Ciphertext#

Plaintext passed through the job's memory and the network, and it can land in anything that captured it. Hunt for the canary in raw and base64 form, since Vault only sees base64:

CANARY=CANARY-5d682357570ff0d9   # yours, from the latest seed run
CANARY_B64=$(printf %s "$CANARY" | base64)
docker compose logs --no-log-prefix | grep -c -e "$CANARY" -e "$CANARY_B64"
docker compose exec old-vault \
  grep -c -e "$CANARY" -e "$CANARY_B64" /vault/logs/audit.log
docker compose exec new-vault \
  grep -c -e "$CANARY" -e "$CANARY_B64" /vault/logs/audit.log
grep -rl -e "$CANARY" -e "$CANARY_B64" .

Container logs and both audit logs came back at 0. Audit devices write a keyed hash (HMAC-SHA256) of most string values by default, so encrypt requests appear as "plaintext":"hmac-sha256:9c917a...". The folder search did find one hit: a transcript I'd saved of the lab run, because seed.py prints the canary. Nobody decides to write plaintext to disk; a print statement does it for them.

Old ciphertext lingers too. Every UPDATE leaves the old row version behind until vacuum:

docker compose exec db psql -U app -d findings -c "
  SELECT relname, n_live_tup, n_dead_tup FROM pg_stat_all_tables
  WHERE relid IN ('findings'::regclass,
    (SELECT reltoastrelid FROM pg_class WHERE relname = 'findings'))"

In my run, findings had 7,075 dead row versions and its TOAST storage (where large values live) had 31,527. VACUUM findings took both to 0, but it only marks the space for reuse (routine vacuuming docs) and never reaches the WAL archive, the source database or backups. Old ciphertext is only dangerous while the old key exists somewhere, including the old Vault's snapshots and backups.

Choice What you get What it costs
Keep the old key for a fixed window A rollback path Every old copy stays readable
Destroy the old key Old copies become unreadable once the key is deleted and the old Vault's storage snapshots and backups are destroyed too No way back

The old key's fate is a decision with an owner and a date, not a cleanup task.

Revoke the job's tokens as soon as the run is verified (python labvault.py revoke); a revoked token gets 403 with invalid token. Destroying a transit key takes two calls; the first is Vault's guard against accidents:

docker compose exec -e VAULT_ADDR=http://127.0.0.1:8200 \
  -e VAULT_TOKEN=old-root old-vault \
  vault write transit/keys/findings-c05/config deletion_allowed=true
docker compose exec -e VAULT_ADDR=http://127.0.0.1:8200 \
  -e VAULT_TOKEN=old-root old-vault \
  vault delete transit/keys/findings-c05

After that, decrypting any old c05 value returns encryption key not found. Remove the lab with docker compose down -v.

  • Zero rows on the old key_ref, skipped rows counted separately
  • Keyed checksum cross-check passed, largest fields included
  • The application reads and writes key_ref
  • Canary search clean across job logs, temp files, staging and CI output
  • Job tokens revoked on both Vaults
  • An owner and a date for destroying the old keys

Troubleshooting#

Symptom Cause Fix
500: JSON string value exceeds allowed length A base64 value exceeds max_json_string_value_length Raise it above your measured largest value (Step 5)
413: http: request body too large A batch exceeds max_request_size Cap batches by bytes, send big rows alone (Step 5)
400: cipher: message authentication failed The ciphertext belongs to the other cluster Route decrypts by key_ref (Step 3)
503: Vault is sealed after a restart A Vault with storage restarts sealed Unseal and re-run; the job resumes (Step 4)

Conclusion#

You built a re-encryption job that survived an interrupt, two size limits and a planted bug, and proved its result without writing plaintext.

What goes wrong What prevents it Step
A crash leaves rows on both keys, indistinguishable A key_ref column and a compare-and-set update 3
A restart redoes work, or stalls on one bad customer Per-customer checkpoints and a circuit breaker 4
One large field kills the run Measured sizes, raised limits, byte-capped batches 5
Rows decrypt but hold the wrong value A keyed checksum cross-check 6
Plaintext or old ciphertext lingers A canary search, token revocation, a decision on the old key 7

What each step bought you.

For a team, the cost is a schema change, a small app change to read through key_ref, a rehearsal at production sizes, and a named owner for destroying the old keys. Skipping them doesn't make the move faster; it moves the work to the night a customer reports half their records won't open.

Next, measure the largest encrypted value in your own tables; that number sets your limits and batch sizes. For the bigger picture, see the GCP to AWS migration case study.

If your team has encrypted data to move between key services, I can review the plan and build the rehearsal that proves it. See how I approach cloud migrations, or book a free 20-minute intro call.

there are no Dumb Questions

(frequently asked questions, answered without judgement)

Can I export the transit keys and import them into the new Vault instead?

Only if every key has exportable and allow_plaintext_backup turned on; Vault refuses a backup otherwise. Both can be switched on later, but never off: once on, the key material can leave Vault in plaintext for good. Restore also refuses a name that already exists unless you pass force. If your security policy allows that, it's faster. If it doesn't, re-encrypt.

Why doesn't the transit rewrap endpoint help when moving Vault clusters?

Rewrap re-encrypts a ciphertext under the latest version of the same named key, inside one Vault, and never returns plaintext. It's the right tool after rotating a key. The new cluster has never seen the old key, so a rewrap there fails with cipher: message authentication failed. Moving between clusters needs a decrypt on the old one and an encrypt on the new one.

Should I re-encrypt online or offline?

Offline, in a maintenance window, is simpler: nothing writes while the job runs. Online, the app reads through both Vaults, picking one by key_ref, and writes every new value under the new key while the job moves old rows in the background. The compare-and-set update protects rows the app rewrites mid-run. It costs dual-read code and a longer period with two live Vaults.

Can I move Vault transit data to AWS KMS the same way?

The method carries over: a key reference per row, per-customer checkpoints, keyed checksum checks. The encrypt call doesn't. KMS Encrypt takes at most 4,096 bytes with a symmetric key, so large fields need envelope encryption: GenerateDataKey returns a data key in plaintext and encrypted, you encrypt the field locally with the data key and store the encrypted data key beside it.

Found this useful? Share it

Cloud MigrationPostgreSQLPythonSecurity

Did that make sense? If not, tell me. Seriously.

Written by an actual human. Any typos are artisanal.

Written by Shahid Yousuf

Senior Software Engineer for backend, distributed and data-intensive systems, AWS infrastructure and AI applications, from the first conversation to production. Work with me, or connect on X and LinkedIn to get the next in-depth tutorial.

Shahid Yousuf

Senior Software Engineer

I build whole products, specialising in backend, distributed and data-intensive systems, AWS and AI. Have something in mind? Let's talk.

Hire me Book a free intro call see the case studies

Get new posts

I share every new in-depth tutorial on X and LinkedIn. Connect with me there to get the next one.

feed reader person? RSS or Atom, very retro, very respected.

(the kettle's still warm)

A tested Python tutorial: see what each PostgreSQL isolation level lets through, overspend a budget three ways, then stop it with SERIALIZABLE retries, a row lock or one UPDATE.

PostgreSQL24 min read

Have a project in mind?

Share your goals, timeline and any constraints, whether you need it built or want expert advice. I'll reply with a clear view on approach, scope and next steps.

Liked the post? The engineer is available too. Same writing style, more code.