Quantum-Ready Data Security: Protecting Legacy Databases and AI Pipelines Without Rewriting Code
Most of the databases I've protected over the years sit behind the applications nobody wants to touch. The code is old, the people who wrote it have moved on, and the business runs on it every day. Those same systems now
Most of the databases I've protected over the years sit behind the applications nobody wants to touch. The code is old, the people who wrote it have moved on, and the business runs on it every day. Those same systems now feed AI projects, and leadership is asking what quantum computing means for all of it.
Three problems now land on the same stack. Attackers can record encrypted traffic today and decrypt it once quantum computers are strong enough, a tactic called harvest now, decrypt later.
AI pipelines copy sensitive records into places the original controls never reached. And nobody is going to fund a rewrite of the applications in the middle.
You don't need one. Most of the protection can live in layers you already own: storage, the network edge, the key manager, and a gateway in front of your models. Below are five steps to get there, with the config and code you can try in a lab.
The Quantum Problem Is Really a Key Problem
A large, error-corrected quantum computer running Shor's algorithm breaks RSA and elliptic-curve cryptography. Those algorithms handle key exchange in TLS, wrap data keys, and sign most of what we trust.
Symmetric encryption is a different story. Grover's algorithm offers only a square-root speedup against brute force, so AES-256 keeps a comfortable margin. In practice, a quantum attacker goes after the way keys move, not the AES-256 encrypting your data files.
That puts the exposure in the asymmetric layer around your data:
- TLS key exchange on database connections, replication streams, and backup transfers.
- Data keys wrapped with RSA public keys for escrow, backup, or cross-site copies.
- The link between encryption agents and the key manager.
The deciding factor is shelf life. Add the years your data must stay secret to the years your migration will take. If that total exceeds the time until a capable quantum machine exists, you're already late.
That's Michele Mosca's rule of thumb, and nobody can give you the last number with confidence. Claims history, clinical records, and trained models can need protection for decades.
The standards aren't the blocker anymore, either. NIST published ML-KEM (FIPS 203) for key establishment, plus ML-DSA (FIPS 204) and SLH-DSA (FIPS 205) for signatures, in 2024.
Why AI Pipelines Raise the Stakes
Follow one claims record through a typical AI project. In the source database, it has encryption, masking, activity monitoring, and access reviews. Then it starts to multiply:
- A CSV extract for feature engineering
- A training snapshot in object storage
- Text chunks and embeddings in a vector database
- Prompt and response logs from a chatbot or agent
- An evaluation set copied to a shared drive
Most of those copies carry none of the source controls, and three things make that worse.
Copies live longer than people expect. Teams keep training data and model versions for reproducibility and audits, often for years. That's exactly the shelf life that makes harvesting now and decrypting later a real concern.
Derived data is still sensitive data. Research on embedding inversion shows that vectors can leak a surprising amount of the original text, and models can memorize and repeat training records. "It's only vectors" is a hard argument to make to a HIPAA auditor.
AI also opens new exits. Prompts travel to external model APIs, and agents get tool access to databases. A poisoned document pulled in during retrieval can instruct an agent to send data where it shouldn't go.
The Core Idea: Wrap the System, Don't Rewrite It
You can't change what the application does, but you control almost everything around it. Four layers carry most of the protection:
- Storage: transparent encryption under the database and every AI data store, with keys held centrally.
- Network edge: a reverse proxy that speaks hybrid post-quantum TLS to clients.
- Key manager: hybrid key wrapping, plus a record of which algorithm protects which key.
- AI gateway: one controlled path between your applications and any model.
Each one is an infrastructure or configuration change. Your platform team can roll it out and roll it back without a release from the application team.
four controls around the legacy app ยท no code changes Only the shaded boxes are new; the application, its clients, and the model provider stay as they are.
Step 1: Inventory Your Crypto and Your Data's Shelf Life
You can't migrate what you can't find. Start with two lists: everywhere asymmetric crypto protects data in motion or wraps a key, and how long each data set must stay confidential.
For the first list, check TLS endpoints, certificates, key manager records, backup settings, and any script that wraps keys itself. This small script covers services that speak TLS directly:
# crypto_inventory.py: what protects each TLS endpoint today?
import socket
import ssl
from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import ec, rsa
ENDPOINTS = [
("claims-api.internal", 443),
("vector-db.internal", 443),
("kms.internal", 5696), # KMIP; may require a client certificate
]
def inspect(host, port):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE # inventory only, never for real traffic
with socket.create_connection((host, port), timeout=5) as sock:
with ctx.wrap_socket(sock, server_hostname=host) as tls:
cert = x509.load_der_x509_certificate(tls.getpeercert(binary_form=True))
key = cert.public_key()
if isinstance(key, rsa.RSAPublicKey):
key_type = f"RSA-{key.key_size}"
elif isinstance(key, ec.EllipticCurvePublicKey):
key_type = f"EC-{key.curve.name}"
else:
key_type = type(key).__name__
return {
"endpoint": f"{host}:{port}",
"tls": tls.version(),
"cipher": tls.cipher()[0],
"cert_key": key_type,
"expires": cert.not_valid_after_utc.date().isoformat(),
}
for host, port in ENDPOINTS:
try:
print(inspect(host, port))
except (OSError, ssl.SSLError) as err:
print({"endpoint": f"{host}:{port}", "error": str(err)})
It reports protocol versions and certificate key types; Step 3 shows how to test the key exchange itself. For databases that switch to TLS inside their own protocol, such as PostgreSQL, use openssl s_client -starttls postgres instead.
Then tag each data set with a shelf life: under 2 years, 2 to 10 years, or longer. Anything long-lived with classic RSA or ECDHE in its path goes to the top of the list.
Step 2: Encrypt at Rest, Below the Application
You have two ways to do this without touching application code. The first is database-native transparent data encryption (TDE), with the master key in an external key manager or HSM. A wallet file on the same server doesn't count.
The second is a transparent encryption agent at the file system or volume layer. I lean toward the agent for mixed estates. One policy covers data files, transaction logs, exports, and backups, plus the AI copies TDE never sees: training snapshots, feature files, and vector indexes.
The policy decides who gets cleartext, and that's where most of the value is:
# Illustrative, vendor-neutral policy
protected_path: /data/claims-db
key: claims-db-kek-2026 # held in the central key manager
rules:
- user: dbsvc # database service account
process: /opt/db/bin/dbserver
access: read_write
sees: cleartext
- user: backupsvc
access: read
sees: ciphertext # backups stay encrypted end to end
- user: any # root and admins included
access: list_only # file names yes, contents never
audit: denials_and_admin_access
Root can't read the data, DBAs never hold the keys, and backups stay encrypted without a second key to manage. Use the same pattern for the training snapshot directory and the vector index, with the training job's account as the only cleartext reader.
The bulk cipher is AES-256, which already has a comfortable quantum margin. What needs attention is how the agent fetches keys from the key manager and how those keys get backed up. Steps 3 and 4 deal with both.
With AES hardware acceleration on current CPUs, the overhead is usually small. Still, measure it against your own I/O pattern before production.
Step 3: Put Hybrid Post-Quantum TLS at the Edge
A hybrid key exchange runs classic X25519 and ML-KEM-768 together and feeds both secrets into the session keys. An attacker has to break both, so you stay covered even if a flaw turns up in the newer algorithm.
Put it on a reverse proxy in front of the legacy app. With nginx linked against OpenSSL 3.5 or newer, it takes a few lines:
server {
listen 443 ssl;
server_name claims.example.internal;
ssl_certificate /etc/nginx/tls/claims.crt;
ssl_certificate_key /etc/nginx/tls/claims.key;
ssl_protocols TLSv1.2 TLSv1.3; # hybrid groups need TLS 1.3
ssl_ecdh_curve X25519MLKEM768:X25519:prime256v1;
location / {
proxy_pass http://127.0.0.1:8080; # legacy app, untouched
}
}
To confirm it works, offer only the hybrid group from a client running OpenSSL 3.5 or newer. If the handshake completes, the server supports it:
openssl s_client -connect claims.example.internal:443 -groups X25519MLKEM768 -brief </dev/null
Recent Chrome releases already offer this group by default, so browser traffic benefits as soon as the proxy does. Apply the same setting to links that carry long-lived data, such as replication, backup targets, and the key manager connection, as each vendor adds support.
Two caveats. The hop from the proxy to the app is still classic, so keep it on the same host or an isolated segment.
Your certificates can stay RSA or ECDSA for now. Authentication happens live during the handshake, so a recording gives an attacker nothing to forge later. The key exchange is the part that gets harvested.
Step 4: Make Key Wrapping Crypto-Agile
Most data at rest already uses envelope encryption: a data key encrypts the data, and a key-encryption key wraps the data key. When that wrap uses RSA, it's the weak link. It's also the easiest piece to fix, because you re-wrap the data keys and the terabytes underneath never move.
The trick is to store an algorithm label with every wrapped key. Old and new schemes then live side by side while a background job migrates. Here's the pattern in Python, using a hybrid X25519 and ML-KEM-768 wrap:
# hybrid_wrap.py: wrap a data key so it stays safe while either X25519 or ML-KEM-768 holds
# Needs a recent "cryptography" release with ML-KEM support: pip install -U cryptography
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey
from cryptography.hazmat.primitives.asymmetric.x25519 import (
X25519PrivateKey,
X25519PublicKey,
)
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
ALG = "X25519+ML-KEM-768/HKDF-SHA256/AES-256-GCM"
def derive_kek(x_secret, pq_secret, transcript):
hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
info=ALG.encode() + transcript)
return hkdf.derive(x_secret + pq_secret)
def wrap(dek, x_pub, pq_pub, context):
eph = X25519PrivateKey.generate()
eph_pub = eph.public_key().public_bytes_raw()
pq_secret, pq_ct = pq_pub.encapsulate()
kek = derive_kek(eph.exchange(x_pub), pq_secret, eph_pub + pq_ct + context)
nonce = os.urandom(12)
return {"alg": ALG, "eph_pub": eph_pub, "pq_ct": pq_ct, "nonce": nonce,
"wrapped": AESGCM(kek).encrypt(nonce, dek, context)}
def unwrap(blob, x_priv, pq_priv, context):
if blob["alg"] != ALG:
raise ValueError(f"No handler for {blob['alg']}") # new schemes plug in here
x_secret = x_priv.exchange(X25519PublicKey.from_public_bytes(blob["eph_pub"]))
pq_secret = pq_priv.decapsulate(blob["pq_ct"])
kek = derive_kek(x_secret, pq_secret, blob["eph_pub"] + blob["pq_ct"] + context)
return AESGCM(kek).decrypt(blob["nonce"], blob["wrapped"], context)
# Demo only: in production the recipient's private keys stay in your key manager or HSM
x_priv, pq_priv = X25519PrivateKey.generate(), MLKEM768PrivateKey.generate()
dek = AESGCM.generate_key(bit_length=256)
context = b"claims-db/2026"
blob = wrap(dek, x_priv.public_key(), pq_priv.public_key(), context)
assert unwrap(blob, x_priv, pq_priv, context) == dek
print(blob["alg"], "| ML-KEM ciphertext:", len(blob["pq_ct"]), "bytes")
The alg field is what makes this agile. When a new scheme arrives, you add a handler and a re-wrap job, and old blobs stay readable until they're migrated. Binding the data set name as context also stops a wrapped key from being swapped onto another data set.
Treat this as a way to understand the pattern, not as production code. In production, the private keys stay in your key manager or HSM, and you use its native hybrid wrapping. Vendors are adding ML-KEM support at different speeds, so ask yours for dates and let that drive the plan.
Step 5: Put a Gateway Between Your Data and Your Models
Most applications that call hosted models use an SDK with a configurable base URL. Point that URL at a gateway you run, and every prompt passes through one place you control:
# The variable name depends on your SDK; the idea doesn't
# Before: the app talks to the model provider directly
LLM_BASE_URL=https://api.model-provider.example/v1
# After: same code, traffic now goes through your gateway
LLM_BASE_URL=https://ai-gateway.internal/v1
At a minimum, the gateway should:
- Swap member IDs, SSNs, card numbers and emails for tokens before a prompt leaves your network
- Log each call with the calling service's identity, into the encrypted storage from Step 2
- Allow only approved models, and use hybrid TLS outbound where the provider supports it
The gateway can swap tokens back in the response, so users see real values and the provider never does.
Then block direct egress from application subnets to public model APIs, so nobody can route around it. For agents, grant read access through masked views with short-lived, narrowly scoped credentials. Treat retrieved documents as untrusted input: no instruction inside a document should trigger a write or an export without human approval.
Finally, sign your datasets and model artifacts so you can prove what's running in production. For artifacts that must stay verifiable for years, plan for ML-DSA or the hash-based SLH-DSA.
Pitfalls to Plan For
A few things tend to bite teams during the first rollout:
- Handshakes get bigger. An ML-KEM-768 public key is 1,184 bytes, so the ClientHello often no longer fits in a single packet. Some older load balancers and inspection devices mishandle that, so test through your real network path.
- Size is the cost, not CPU. ML-KEM itself is fast, but measure latency on your own traffic before and after.
- Old crypto hides in slow paths. Backups, replicas, archive tiers and DR copies often keep the oldest settings the longest.
- Everything now depends on the key manager. Cluster it, back it up, and tightly control who can export keys.
- Hand-rolled crypto stays in the lab. Use your platform's supported implementations for anything real.
A Rollout Plan That Fits Real Change Windows
Steps 2 and 3 can run in parallel when different teams own them.
Final Thoughts
Quantum risk, AI data sprawl and legacy code usually show up as three projects with three budgets. They share one root: sensitive data moving through paths you don't fully control, protected by keys that still move the old way. Fix the paths and the keys, and you make progress on all three without waiting for a rewrite nobody will fund.
Start with one long-lived data set. Trace every copy, wrap each layer around it, and write down what you learned. The second data set goes much faster.
Next Steps
In a follow-up post, I'll go deeper on the AI gateway. That covers tokenizing identifiers without breaking prompts, enforcing model allow-lists, and producing audit evidence a HIPAA or PCI assessor will accept. If you're working through a migration like this, tell me in the comments what's slowing you down.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.
