cd /news/ai-tools/i-used-an-ai-agent-to-build-a-post-q… · home › topics › ai-tools › article
[ARTICLE · art-180310] src=github.com ↗ pub= topic=ai-tools verified=true sentiment=· neutral

I used an AI agent to build a Post-Quantum Crypto compiler

A developer released PQC-Sweep v0.3, an early-preview Python tool that traces pandas encryption lineage to specific database columns, generates idempotent SQL column widenings for larger post-quantum ciphertexts, and rewrites RSA encrypt/decrypt calls to a hybrid X25519 + ML-KEM-768 (X-Wing) envelope with RSA dual-read fallback. The tool, tested in CI and on 10 public repositories, emits CycloneDX 1.6 CBOMs and is positioned as complementary to broad scanners such as IBM CBOMkit and OWASP cdxgen, but its author states it has not been independently audited. The release targets Harvest Now, Decrypt Later risk ahead of NIST IR 8547 (final, October 2026), which deprecates 112-bit-security parameters such as RSA-2048 after 2030 and disallows quantum-vulnerable public-key algorithms at any key size after 2035.

key takeaway

PQC-Sweep v0.3 rewrites RSA encrypt/decrypt calls to a hybrid X25519 + ML-KEM-768 envelope that keeps decrypting pre-migration rows with the original RSA key, and generates idempotent SQL column widenings for the larger ciphertexts.

read11 min views15 publishedDec 2, 2026
I used an AI agent to build a Post-Quantum Crypto compiler
Image: Michielbdejong (auto-discovered)

The last mile of post-quantum migration for data engineering. Finding RSA in your code is the easy part. The hard part is the encrypted column in your warehouse: which table it lands in, whether the bigger post-quantum ciphertext still fits, and how to switch over without breaking every reader of the rows already written.

PQC-Sweep does that part, deterministically, on your machine:

  1. Traces pandas lineage. It followsdf['email'].apply(encrypt_fn) across files, through renames and helpers, to the exacttable.column it's written to (to_sql , SQLAlchemy ORM).
  2. Generates idempotent SQL column widenings. A migration for each affected column, safe to run twice, that skips columns already wide enough and refuses to touch types it can't safely convert.
  3. Injects a dual-read fallback envelope. RSA encrypt/decrypt calls are rewritten to ahybrid X25519 + ML-KEM-768 envelope (X-Wing). Rows written before the migration keep decrypting with the original RSA key and padding.

Status: early preview (v0.3). Tested in CI and on 10 public repositories (validation report). The envelope uses standard primitives and is checked against the X-Wing draft's test vectors, but it has not been independently audited. Read Scope and limits before using it on production code.

While tools like IBM CBOMkit handle broad language detection, pqc-sweep is purpose-built for the last mile of data engineering: tracing pandas lineage, generating idempotent SQL column widenings, and injecting dual-read fallback envelopes.

Broad crypto scanners (e.g. IBM CBOMkit / sonar-cryptography ,OWASP cdxgen ) PQC-Sweep
Languages Java, Python, Go and more Python only
CycloneDX CBOM Yes Yes (1.6, schema-validated)
Encrypted value → database column Not their focus Yes: pandas lineage to to_sql / ORM table and column
Schema migration for larger ciphertexts No Yes: idempotent PostgreSQL DO blocks; MySQL, SQL Server, SQLite
Code rewrite No (inventory) Yes: RSA encrypt/decrypt → hybrid envelope with RSA dual-read

Use them together: a broad scanner for the estate-wide inventory, PQC-Sweep for the Python pipelines that write encrypted data into databases. (Comparison based on each project's public documentation as of December 2026.)

Encrypted data that leaves your perimeter today can be recorded and stored. An attacker doesn't need to break RSA now. They only need to keep the ciphertext until a cryptographically relevant quantum computer can. This is Harvest Now, Decrypt Later (HNDL). Data with a long confidentiality life is exposed today, even though the decryption happens later. That includes client PII, KYC records, account data and anything regulated for years or decades.

Data pipelines are where this risk concentrates. They encrypt PII column by column, write the ciphertext into warehouses and keep it for years.

The deadline is now published. NIST IR 8547, Transition to Post-Quantum Cryptography Standards (final, October 2026), sets the schedule for quantum-vulnerable public-key algorithms (RSA, ECDSA, EdDSA, DH, ECDH):

  • Deprecated after 2030. This covers 112-bit-security parameters such as RSA-2048.
  • Disallowed under NIST standards and guidelines after 2035 , at any key size.

The report supports Executive Order 14412 and OMB Memorandum M-26-15, which direct US federal agencies to prioritise moving their most sensitive systems to post-quantum cryptography. The replacement for RSA key establishment is ML-KEM (FIPS 203). Sources: NIST IR 8547 (CSRC) · full text

ML-KEM is new. X25519 is well studied but quantum-vulnerable. A hybrid KEM combines both, so stored data stays confidential unless both are broken. That is the transition pattern most of the industry has adopted.

PQC-Sweep uses X-Wing (draft-connolly-cfrg-xwing-kem-11), a concrete X25519 + ML-KEM-768 hybrid KEM with a SHA3-256 combiner. The implementation reproduces the draft's published test vectors for key generation and decapsulation. Its shared secret goes through HKDF-SHA256 into AES-256-GCM.

Asking an LLM to "upgrade our crypto" is the wrong tool for this job:

  • Output is probabilistic. The same prompt can yield different code. A rewrite that looks right can still pick the wrong padding, drop a key path or invent an API, and in cryptography a plausible-looking mistake is a silent vulnerability.
  • There's no audit trail you can defend. A generated diff can't provewhy each change was made or that nothing was missed.
  • Your code and data leave the building. Sending proprietary ETL, schemas and sample data to a hosted model widens the very exposure you're trying to close.

PQC-Sweep applies fixed rules to the program's syntax tree:

  • It finds RSA wherever the key comes from. Thecryptography RSA API always takes an explicit padding object (OAEP ,PKCS1v15 ,PSS ). PQC-Sweep matches on that padding, so it finds RSA encryption, decryption and signing whether the key is generated locally, loaded from PEM, passed in as a parameter or held onself .
  • Narrow, reversible rewrites. Only RSAencrypt /decrypt call sites change. Key-generation code, signatures and ECC are reported, never rewritten. Developer comments and formatting are kept (libcst).
  • Nothing is guessed. A dynamic table name is reported asUNRESOLVED , never invented, and--strict fails the CI run when that happens. Encrypt sites whose recipient key comes from elsewhere are flagged for human review.
  • It runs entirely on your machine. No network calls, no model, and no data leave your machine.
 def encrypt_pii(data_string):
-    private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
-    public_key = private_key.public_key()
 
-    ciphertext = public_key.encrypt(
-        data_string.encode(),
-        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
-    )
+    ciphertext = QuantumSafeHybridEnvelope().encrypt_bytes(data_string.encode(), load_pqc_public_key())
     return base64.b64encode(ciphertext).decode()
 
 
 def decrypt_pii(token, private_key):
-    plaintext = private_key.decrypt(
-        base64.b64decode(token),
-        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
-    )
+    plaintext = QuantumSafeHybridEnvelope().decrypt(base64.b64decode(token), {'pqc': load_pqc_private_key, 'rsa': private_key}, legacy_padding=padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
     return plaintext.decode()
  • Encrypt calls becomeencrypt_bytes(...) , which still returnsbytes , so code that base64-encodes or stores the result keeps working.
  • Decrypt calls keep the original RSA key and padding as a fallback. Rows written before the migration still decrypt, and the post-quantum private key is only loaded when a post-quantum value is read.
  • Key generation that is no longer used is removed. Imports are tidied, and comments stay.

migration.sql : DDL that widens every ciphertext column PQC-Sweep traced to fit the hybrid envelope (about 2k characters, against about 344 for RSA-2048 in base64). On PostgreSQL each change is anidempotent DO block :

  • TEXT and wide-enoughVARCHAR columns are skipped;
  • short VARCHAR /CHAR columns are widened;
  • incompatible types such as BYTEA stop the migration rather than corrupting data. MySQL, SQL Server and SQLite are also supported.

pqc_envelope.py : the runtime that gets injected. X-Wing (X25519 + ML-KEM-768) → HKDF-SHA256 → AES-256-GCM viacryptography , in a binary format (encrypt_bytes ) and a text format (pqc:v2:xwing:... ). It reads legacy RSA ciphertext with the caller's original padding, and ML-KEM-only values written by pqc-sweep 0.2. If ML-KEM is unavailable it refuses to run rather than producing insecure output. 3. Rewritten source : originals are backed up to.pqc_sweep/backup/ .--dry-run shows the plan without touching anything. 4. cbom.json : a CycloneDX 1.6 Cryptographic Bill of Materials. Every RSA/ECC asset (key generation, encryption, decryption, signatures, and PyCryptodome usage) is taggednistQuantumSecurityLevel: 0 , with the source location, the taint flow, the database table it lands in and a remediation note. It is validated against the official schema in the test suite, and literal values from source are redacted so PII never reaches the report.

pip install pqc-sweep                                   # Python 3.9+; installs the pqc-sweep command
pqc-sweep --repo path/to/your/etl --dry-run --strict    # report and plan only: CBOM + DDL + what would be rewritten
pqc-sweep --repo path/to/your/etl                       # full sweep (originals backed up to .pqc_sweep/backup/)

The rewritten code needs cryptography (with ML-KEM support) in the target project: pip install "pqc-sweep[runtime]" or add cryptography>=46 to its requirements.

From source (to run the tests or the bundled demo):

git clone https://github.com/baldersonjames6-lang/pqc-sweep && cd pqc-sweep
python3 -m venv .venv && .venv/bin/pip install --upgrade pip   # editable installs need pip >= 21.3 (macOS system Python ships 21.2)
.venv/bin/pip install -e '.[dev]'      # add ,pg-embedded to run the live PostgreSQL tests locally
.venv/bin/pqc-sweep --repo examples/demo_pipeline
🔍 Initializing config-time PQC Sweep...
   scanned 2 module(s); 3 quantum-vulnerable asset(s); 1 taint flow(s)
   PQC-001 main_pipeline.py:13 df['client_email'] -> crypto_utils.encrypt_pii(data_string) -> df['secure_email']
          DB SINK client_secure_vault.secure_email <- main_pipeline.py:17 pandas.to_sql
   CBOM  -> examples/demo_pipeline/cbom.json (CycloneDX 1.6, 2 component(s))
   DDL   -> examples/demo_pipeline/migration.sql (postgresql, 1 ALTER statement(s) guarded by idempotent DO block(s), VARCHAR(2048))
          ALTER TABLE "client_secure_vault" ALTER COLUMN "secure_email" TYPE VARCHAR(2048);
   RUNTIME -> examples/demo_pipeline/pqc_envelope.py
   MUTATED crypto_utils.py: encrypt_pii (encrypt x1), decrypt_pii (decrypt x1) [libcst, comments preserved]
✅ Transpilation complete. CBOM, SQL DDL, and Quantum-Safe Code generated.

Running the rewritten code:

  • Set PQC_XWING_PUBLIC_KEY to the X-Wing public key file (1216 raw bytes) where data is encrypted, andPQC_XWING_PRIVATE_KEY to the 32-byte private seed where post-quantum values are decrypted.
  • pqc_envelope.generate_keypair(dir) creates a test pair. Keep real keys in your KMS or secret store.
  • Upgrading from 0.2: values written by 0.2 (pqc:v1:mlkem768 ) still decrypt if you pass the old ML-KEM key as'mlkem' (e.g.{'pqc': load_pqc_private_key, 'mlkem': load_mlkem_private_key, 'rsa': key} ). Call sites rewritten by 0.2 keep working but write non-hybrid values with aDeprecationWarning , so re-run the sweep or update them toload_pqc_public_key() .

The generated PostgreSQL migration (excerpt):

DO $pqc$
DECLARE
    v_type text;
    v_len integer;
BEGIN
    SELECT data_type, character_maximum_length INTO v_type, v_len
    FROM information_schema.columns
    WHERE table_schema = current_schema()
      AND table_name = 'client_secure_vault'
      AND column_name = 'secure_email';
    IF NOT FOUND THEN
        RAISE WARNING 'pqc-sweep: % not found, nothing altered', 'client_secure_vault.secure_email';
    ELSIF v_type = 'text' OR (v_type = 'character varying' AND (v_len IS NULL OR v_len >= 2048)) THEN
        RAISE NOTICE 'pqc-sweep: % already holds % chars (%), skipped', 'client_secure_vault.secure_email', 2048, v_type;
    ELSIF v_type IN ('character varying', 'character') THEN
        ALTER TABLE "client_secure_vault" ALTER COLUMN "secure_email" TYPE VARCHAR(2048);
        RAISE NOTICE 'pqc-sweep: % widened to VARCHAR(2048)', 'client_secure_vault.secure_email';
    ELSE
        RAISE EXCEPTION 'pqc-sweep: % is %, which needs a manual data migration', 'client_secure_vault.secure_email', v_type;
    END IF;
END
$pqc$;

The CBOM entry (excerpt from examples/demo_pipeline/cbom.json):

{
  "type": "cryptographic-asset",
  "name": "RSA-2048",
  "cryptoProperties": {
    "assetType": "algorithm",
    "algorithmProperties": { "primitive": "pke", "parameterSetIdentifier": "2048", "cryptoFunctions": ["encrypt", "keygen"],
                             "classicalSecurityLevel": 112, "nistQuantumSecurityLevel": 0 },
    "oid": "1.2.840.113549.1.1.1"
  },
  "properties": [
    { "name": "pqc-sweep:taint-flow", "value": "PQC-001 main_pipeline.py:13 df['client_email'] -> crypto_utils.encrypt_pii(data_string) -> df['secure_email']" },
    { "name": "pqc-sweep:taint-origin", "value": "PQC-001 pd.DataFrame({'client_email': ['<redacted>']})" },
    { "name": "pqc-sweep:db-sink", "value": "PQC-001 client_secure_vault.secure_email <- main_pipeline.py:17 pandas.to_sql" }
  ]
}

CLI options:

  • --dialect postgresql|mysql|mssql|sqlite
  • --max-plaintext-bytes N sets column sizing. The default is 320 bytes, which givesVARCHAR(2048) ; above 374 bytes it moves toVARCHAR(4096) .
  • --dry-run reports and plans without changing files.
  • --strict exits with code 2 on unresolved sinks.
  • --no-cst forces the standard-library rewriter, which drops comments.

Tests. 108 tests run in CI on every push and PR to main (Python 3.10 and 3.13, against a postgres:16 service container). They cover:

  • taint and lineage resolution;
  • DDL for every dialect, including escaping;
  • the idempotent migration executed twice against a real PostgreSQL 16 ;
  • an end-to-end run where the rewritten pipeline writes to SQLite and the same rewritten decrypt_pii reads both the new hybrid value and a legacy RSA value;
  • X-Wing key generation and decapsulation against the draft's published test vectors;
  • envelope round trips in both formats, reading 0.2 ML-KEM-only values, the legacy RSA fallback with its original padding, lazy key and tamper rejection;
  • comment and line-ending preservation, and a guarantee that key-generation code is never rewritten;
  • CycloneDX 1.6 strict-schema validation and PII redaction.

Real code. Swept against 10 public GitHub repositories (2,272 Python files):

  • 61 crypto assets found;
  • 20 encrypt and 17 decrypt call sites rewritten;
  • every rewritten file still compiles;
  • no key-generation helper modified.

The method, pinned commits and the bugs this found are in docs/real-world-validation.md.

  • Python only, one crypto library rewritten. Thecryptography package's RSA is rewritten. PyCryptodome and ECC are reported in the CBOM but not rewritten. RSA signatures are reported with an ML-DSA (FIPS 204) note but not rewritten. For other languages, use a broad scanner such as CBOMkit.
  • Database writes. These are traced throughDataFrame.to_sql and SQLAlchemy ORM. SQLAlchemy Coreinsert() ,executemany , raw DB-API cursors and Spark aren't traced yet.merge /concat /pivot stop the lineage rather than guess.
  • Recipient keys. The rewrite encrypts to the single post-quantum key configured for the deployment. That's right for data at rest. Where code encryptsto a specific party's key (key transport, multi-tenant keys), it changes behaviour, so those sites are printed asREVIEW lines for a human to decide.
  • Python version. The scanner can only parse syntax that the Python running it understands, so run it on the newest Python your codebase targets. Files it can't parse are listed, not silently ignored.
  • Existing data. The DDL changes column types only. Existing rows stay readable through the RSA fallback until you re-encrypt them.
  • Key management. Generating, storing and rotating the X-Wing keys is your KMS's job.
  • X-Wing is still an Internet-Draft. The construction may change before it becomes an RFC; the envelope format is versioned (pqc:v2 ) so a later change can be read alongside it.
  • No audit yet. The envelope uses standard primitives fromcryptography and matches the X-Wing test vectors, but has not had an independent cryptographic review.

Bug reports, especially missed crypto (false negatives) and wrong rewrites, are the most valuable contribution. See CONTRIBUTING.md. Please report vulnerabilities privately as described in SECURITY.md.

Apache License 2.0. Copyright 2026 James Balderson. See LICENSE and NOTICE.

── more in #ai-tools 4 stories · sorted by recency
── more on @pqc-sweep 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/i-used-an-ai-agent-t…] indexed:0 read:11min 2026-12-02 · —