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 Source:https://dev.to/shahidyousuf/how-to-move-vault-encrypted-data-to-new-keys-safely-1pl9

Related posts