Writing Field-Level Encryption Code With LLMs in November 2026: Use an AEAD From a Vetted Library, Never Reuse a Nonce, and Plan Key Rotation on Day One

Sooner or later a product stores something that should not sit in the database as plain text: a tax ID, a bank account number, an API token a customer handed you, a medical note. Disk encryption and TLS do not help much here, because anyone who can run a query, read a backup, or open a database dump still sees the value. Field-level encryption closes that gap by encrypting specific columns in your application before they ever reach the database.

It is also a place where LLM-generated code goes wrong in quiet ways. The code runs, the round-trip test passes, and the flaw only matters when someone attacks it. This post covers how to ask a model for encryption code you can actually ship, what to check in what it gives you, and the tests that catch the common mistakes.

Exploded view of an Enigma machine rotor

Encryption is easy to get subtly wrong, which is why you should lean on vetted, well-studied designs. Image: Enigma rotor exploded view by Wapcaplet, CC BY-SA 3.0, via Wikimedia Commons.

Decide what you are protecting against first

Before you prompt anything, write down the threat in one or two sentences. Field-level encryption is good at a specific job: someone gets a copy of the data (a leaked backup, a read-only SQL injection, an over-permissioned analyst account) but does not get the encryption key. It does nothing if the attacker controls your application server, because the server has to hold or fetch the key to decrypt.

Answer these before you write a prompt:

  • Which columns? List them. Encrypting everything makes searching, sorting, and debugging painful for little gain.
  • Who needs the plain value? If only one service reads it, only that service should be able to fetch the key.
  • Do you need to look rows up by this value? If yes, you need a separate blind index (covered below), because normal encrypted values cannot be searched.
  • Where will the key live? A cloud KMS, a secrets manager, or at minimum an environment secret that is not in the repository or the database.

Paste these answers into the prompt. A model that knows "one service, two columns, lookups by email required, keys in a KMS" writes far better code than one asked to "add encryption to the users table".

Ask for an AEAD from a vetted library, by name

The single most useful line in your prompt is the one that names the primitive and the library. Ask for authenticated encryption with associated data (AEAD), such as AES-256-GCM or XChaCha20-Poly1305, from a maintained library: cryptography in Python, libsodium bindings, Go's standard crypto/cipher, Google's Tink, or your platform's equivalent. Say explicitly that you do not want a hand-written cipher mode.

Things to reject when you see them in generated code:

  • ECB mode. Identical plaintext blocks produce identical ciphertext blocks, which leaks patterns.
  • CBC or CTR without a MAC. Unauthenticated ciphertext can be modified without detection, and CBC padding errors have a long history of turning into decryption oracles.
  • A key derived from a hard-coded string, such as hashing a passphrase in the source file.
  • Base64 or XOR "encryption". Models still produce this occasionally when the prompt says "obfuscate".
  • Password hashing functions used as encryption. bcrypt or Argon2 are one-way; they are for passwords you verify, not values you need back.

A minimal Python version using AES-256-GCM looks like this:

import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

NONCE_LEN = 12  # 96-bit nonce, the standard size for GCM

def encrypt_field(key: bytes, plaintext: str, aad: bytes) -> bytes:
    nonce = os.urandom(NONCE_LEN)
    ct = AESGCM(key).encrypt(nonce, plaintext.encode("utf-8"), aad)
    return nonce + ct  # store the nonce with the ciphertext

def decrypt_field(key: bytes, blob: bytes, aad: bytes) -> str:
    nonce, ct = blob[:NONCE_LEN], blob[NONCE_LEN:]
    return AESGCM(key).decrypt(nonce, ct, aad).decode("utf-8")

This is short on purpose. Encryption code should be small enough to review line by line. If the model hands you two hundred lines of custom padding and block handling, start over with a narrower prompt.

Never reuse a nonce with the same key

AES-GCM requires that a nonce is never used twice with the same key. If it is, an attacker who sees both ciphertexts can learn the XOR of the two plaintexts and can recover the authentication subkey, which lets them forge messages. This is the mistake LLM code makes most often, usually in one of these forms:

  • A nonce defined once as a module-level constant.
  • A nonce derived from the row ID or a timestamp, which repeats after a restore, a retry, or two writes in the same millisecond.
  • A counter kept in memory, which resets when the process restarts.

The simple rule: generate a fresh random nonce for every encryption with the operating system's secure random source (os.urandom, crypto.randomBytes, crypto/rand) and store it next to the ciphertext. With 96-bit random nonces, NIST guidance limits a single GCM key to about 232 encryptions; if you expect to write more than that under one key, rotate keys sooner or use XChaCha20-Poly1305, whose 192-bit nonce makes random generation safe for far larger volumes.

Bind each ciphertext to its row with associated data

Authenticated encryption detects tampering, but by itself it does not stop someone with database write access from copying a valid ciphertext from one row to another. If user A's encrypted bank account number is pasted into user B's row, it decrypts cleanly.

The fix is the "associated data" input. Pass something that identifies where the value belongs, for example b"users:4821:bank_account" (table, primary key, column). It is not secret and not stored inside the ciphertext, but decryption fails unless the same value is supplied. Ask the model to build the associated data from the table, primary key, and column name, and to use the same function on both the encrypt and decrypt paths.

One catch: if you encrypt before the row has an ID (an auto-increment insert), you need either client-generated IDs such as UUIDs or a second write. Tell the model which one your schema uses so it does not quietly pass empty associated data.

Plan key rotation before you encrypt the first row

Keys leak, staff leave, and compliance policies ask for rotation. If your ciphertext format has no way to say which key encrypted it, rotation means a risky big-bang migration. Add a small header from the start:

[1 byte format version][4 byte key ID][12 byte nonce][ciphertext + tag]

With a key ID in every value, rotation becomes routine:

  1. Add the new key to the key ring and make it the one used for new writes.
  2. Keep the old key available for decryption only.
  3. Run a background job that reads each row, decrypts with whatever key its header names, and re-encrypts with the current key. Make it resumable and safe to run twice.
  4. When no rows reference the old key ID, retire it.

Many teams use envelope encryption here: a key management service holds a key-encryption key that never leaves it, and your app stores data keys that are themselves encrypted by that key. The app asks the KMS to unwrap a data key at startup or on demand. Ask the model to keep the KMS call behind a small interface so you can swap in a local test key ring in unit tests.

A cabinet of labeled keys on hooks

Label every key so you always know which one locked which value. Image: Key cabinet by Thomas Quine, CC BY 2.0, via Wikimedia Commons.

Searching encrypted columns: use a blind index, and know what it leaks

Random nonces mean the same email encrypts differently every time, so WHERE email = ? stops working. Models sometimes "fix" this by switching to a fixed nonce. Do not accept that; it brings back the nonce-reuse problem.

The standard approach is a blind index: a separate column holding an HMAC-SHA256 of the normalized value under a different key. To look up a user, compute the HMAC of the search term and query that column. Points to put in the prompt:

  • Use a separate key for the index, never the encryption key.
  • Normalize before hashing (trim, lowercase emails) so lookups match.
  • Accept the trade-off: equal values have equal index entries, so someone with the database can tell which rows share a value. For low-variety fields such as country or yes/no flags, that can reveal the value itself, so do not blind-index those.

Range queries, sorting, and partial matches do not work on either column. If you need them, that field is probably not a good candidate for application-level encryption.

Keep plaintext out of the places it leaks to

Encrypting the column is wasted if the plain value ends up somewhere else. Ask the model to review the surrounding code, not just the crypto helper, for these leaks:

  • Logs and error messages that print the model object or request body.
  • ORM __repr__ or toString methods that include every field.
  • Analytics events and error trackers that capture request payloads.
  • Caches and search indexes that store the decrypted object.
  • The keys themselves in config files, Docker images, or CI output.

A useful follow-up prompt: "List every place in this diff where the decrypted value of tax_id could be written to a log, cache, response, or third-party service."

Tests that catch the real mistakes

A round-trip test (encrypt, decrypt, compare) proves almost nothing; a fixed nonce and missing associated data both pass it. Ask the model for these tests as well, and run them:

  1. Nonce uniqueness: encrypt the same value 10,000 times and assert every stored nonce is different.
  2. Ciphertext differs: encrypting the same plaintext twice produces different blobs.
  3. Tamper detection: flip one byte of the ciphertext and assert decryption raises an authentication error (for example InvalidTag in Python's cryptography), rather than returning garbage.
  4. Row binding: decrypting with another row's associated data fails.
  5. Rotation: a value encrypted under key 1 still decrypts after key 2 becomes current, and the re-encryption job moves it to key 2.
  6. Wrong key: a value fails to decrypt with an unrelated key, and the error does not include the plaintext or key material.

A prompt template you can reuse

Add application-level encryption for users.tax_id and users.bank_account
in our Python 3.12 / SQLAlchemy service.

- Threat: protect against leaked backups and read-only DB access.
- Use AES-256-GCM from the "cryptography" package. No custom modes.
- Fresh 12-byte nonce from os.urandom per encryption, stored with the ciphertext.
- Associated data = f"users:{user.id}:{column}". IDs are UUIDs set before insert.
- Blob format: version byte, 4-byte key ID, nonce, ciphertext+tag.
- Keys come from a KeyRing interface (KMS in prod, in-memory in tests).
- Add a blind index column for email lookups using HMAC-SHA256 with a separate key.
- Write tests for nonce uniqueness, tamper detection, AAD mismatch,
  and decrypting under a retired key.
- Do not log or repr any decrypted value.

Checklist before you merge

  • The primitive is an AEAD from a maintained library, named in the code.
  • Every encryption call generates a fresh random nonce.
  • Associated data ties each value to its table, row, and column.
  • The stored format includes a version and key ID.
  • Keys are not in the repository, the database, or the logs.
  • Blind indexes use a separate key and only cover fields that need lookups.
  • The tamper, AAD, nonce, and rotation tests exist and pass.

LLMs are genuinely helpful for the plumbing around encryption: wiring the ORM hooks, writing the migration job, and generating the test cases. Keep the cryptographic decisions in your own hands, state them in the prompt, and check the generated code against them line by line.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)