“We encrypt the data” means nothing. It is a sentence that turns up in audits, contracts and product pages, and it can describe three things with radically different levels of protection.
This article is about the third one, the one that actually protects, and about the problem it creates: once you properly encrypt a field, it stops being searchable. And about how you buy part of that back without undoing the protection, with the cost measured rather than estimated.
Three layers, three different threats
Disk encryption. The volume is encrypted. It protects against somebody walking off with the physical disk, or recovering a badly deleted backup. It protects against absolutely nothing that arrives as a SQL query, because as far as the engine is concerned the volume is mounted and decrypted. If your threat is a leak through the application, this layer does not participate.
Column encryption. The engine encrypts and decrypts for you. Better, but the engine holds the key: anyone who can query can read. And anyone with a dump plus the keys can too.
Field-level encryption. The application encrypts before writing and decrypts after reading. The database never sees plaintext and does not hold the key. A full database dump is noise. This is the only one that protects the scenario that actually matters when you hold sensitive data: somebody with legitimate database access, or with a dump, reading what they should not.
AES-GCM per field, and the parameter almost everyone leaves empty
Authenticated encryption is what you want: it guarantees confidentiality and that the data has not been tampered with. With AES-GCM, the interesting part is not the key — it is the third argument:
def encrypt(self, plaintext: str, aad: bytes) -> Encrypted:
nonce = os.urandom(12)
ct = AESGCM(self._keys[self.current]).encrypt(nonce, plaintext.encode(), aad)
return Encrypted(ct, nonce, self.current)
That aad is additional authenticated data: it is not encrypted, but it is authenticated. If it does not match on decryption, decryption fails. And that is where its usefulness goes well beyond integrity:
decrypts with the correct AAD: ana@example.com
with another tenant's AAD: InvalidTag — does not decrypt
That AAD was tenant=1111|table=patients|col=email. By putting the tenant identifier, the table and the column inside the AAD, you bind the ciphertext to its place. A ciphertext copied from one customer’s row into another’s stops decrypting. A value moved from the email column to the notes column stops decrypting. Without an AAD both of those attacks work and leave no trace: the data decrypts perfectly in a context that is not its own.
And yet the aad argument is the one I have most often seen left blank, because it is optional and the code works fine without it.
The other field that is not optional is the key version. It goes in the row itself, alongside the ciphertext and the nonce. Without it there is no rotation: I get to that at the end, and it is the part that hurts.
What you lose by encrypting the field
Here is the real problem, and it is purely practical. AES-GCM ciphertext carries a random nonce, so two rows with the same email produce different bytes. Consequently:
- Equality:
WHERE email = ?stops working. You cannot encrypt the search term and compare, because the nonce would differ. - Uniqueness: a unique index on the encrypted column prevents nothing.
- Ordering and prefix:
ORDER BY,LIKE 'ana%', ranges. All out.
In practice this gets discovered late, once the compliance requirement is already agreed and it is time to implement. And the first instinct is usually the worst one: decrypt the whole table in memory and filter in the application.
The blind index
The idea is simple: alongside the ciphertext you store a deterministic HMAC of the same string, keyed with a secret only the application holds.
def blind_index(self, plaintext: str, version: int | None = None, bits: int = 256) -> bytes:
v = self.current if version is None else version
full = hmac.new(self._blind[v], plaintext.encode(), hashlib.sha256).digest()
return full[: bits // 8]
Deterministic means the same text always produces the same value, so you can search: hash what you are looking for and compare. And because it is a keyed HMAC, somebody holding the database without the key cannot test candidates.
It has to be an HMAC and not a plain hash. With sha256(email) and no key, anyone with the dump runs through whatever dictionary of addresses they like and checks off the hits. The key is what turns a hash into something that cannot be attacked offline.
The first thing that bites: it normalizes nothing
same text -> same index: True
different text -> different index: True
case-insensitive by itself? False
ana@example.com and ANA@example.com produce completely different indexes. With citext or a LOWER() in the database you got that for free; with a blind index, normalization becomes your responsibility and you have to decide it once, for good. Lowercasing, Unicode NFKC, trimming whitespace, perhaps stripping dots from the local part of an address.
And the trap: the day you change the normalization, every blind index written before stops matching. It is the same class of problem as key rotation, and just as quiet.
What it buys back, and what it does not: measured
I loaded 300,000 rows into PostgreSQL 18.4 with realistic-length emails (28.3 characters on average), the encrypted column, its unique 16-byte blind index, and — purely to compare plans — a plaintext column that would not exist in production. In the SQL script a truncated sha256 stands in for the HMAC: PostgreSQL has no HMAC without extensions, and for what is measured here — size and distribution in the index — it behaves the same.
Equality: recovered, and free.
── via the blind index ──
Index Scan using uq_bidx on patients (actual rows=1.00)
Index Searches: 1
Buffers: shared hit=1 read=3
── the same equality on plaintext ──
Index Scan using idx_plain on patients (actual rows=1.00)
Index Searches: 1
Buffers: shared hit=1 read=3
Identical. Four buffers (one already cached, three read) and one index search in both cases. The same unique index that enforces uniqueness serves the lookup: there is no need for a second index on the same column. This is the number that surprised me most for how rarely it is stated: an equality lookup on an encrypted field costs no more than on plaintext. The cost of field-level encryption is not in the query.
Uniqueness: recovered. A unique index on (tenant_id, email_bidx) works:
ERROR: duplicate key value violates unique constraint "uq_bidx"
Ordering: not recovered, and the failure is silent. ORDER BY email_bidx raises nothing; it orders by the HMAC:
ORDER BY email_bidx ORDER BY email_plain
carmen.gil146728@hotmail.com alberto.alonso100195@gmail.com
marta.sanchez234472@hotmail.com alberto.alonso100595@hotmail.com
laura.navarro141830@empresa.com alberto.alonso100995@outlook.es
Perfectly plausible results in an order that means nothing. If that feeds a paginated list, you have pagination that is stable and arbitrary, which is worse than pagination that breaks.
Prefix: not recoverable at all. No operator can exploit an HMAC for LIKE 'ana%', because an HMAC does not preserve prefixes by design. If you need prefix search over an encrypted field, the blind index is the wrong tool and the requirement needs redesigning.
And disk, which comes out cheaper than expected:
whole table: 90 MB · blind index: 17 MB · plaintext index: 20 MB
The blind index is smaller than the text index, because 16 fixed bytes weigh less than an email averaging 28 characters. The space cost is in the table: the ciphertext, with its 12-byte nonce and 16-byte tag, takes 56.3 bytes per row against 28.3 for the plaintext email.
The leak that remains, and it is real
This is what has to be understood before approving a design with blind indexes. I took 10,000 rows with a status column of five values in a realistic distribution and computed their blind indexes:
rows: 10,000 · distinct values in the column: 5
distinct blind indexes: 5
group 1: 6000 rows (60.0%)
group 2: 2500 rows (25.0%)
group 3: 1000 rows (10.0%)
group 4: 400 rows ( 4.0%)
group 5: 100 rows ( 1.0%)
Whoever holds the dump cannot decrypt a single value. But they can see how many distinct values the column has, and the exact frequency of each. With any known distribution for the domain — clinical statuses, contract types, incident categories — the 1% group is identified by elimination. And from there, every row in that group is classified.
What leaks is not the data: it is the structure. And in a low-cardinality column, the structure is the data.
And truncating does not fix it the way it is usually claimed
The standard mitigation is to truncate the HMAC so that several values collide on purpose and blur together. I measured it over 200,000 distinct values:
| bits | distinct | collisions | rows per lookup |
|---|---|---|---|
| 16 | 62,398–62,482 | 137,518–137,602 | 4.05 |
| 24 | 198,748–198,840 | 1,160–1,252 | 1.01 |
| 32 | 199,993–199,996 | 4–7 | 1.00 |
| 48 | 200,000 | 0 | 1.00 |
| 64+ | 200,000 | 0 | 1.00 |
The keys are random on every run, so the ranges come from five runs; the shape of the table is the result, not the individual figures.
The conclusion is uncomfortable: for truncation to blur anything you have to go down to 16 bits, and at that point every lookup returns roughly four rows you have to decrypt and filter in the application. At 24 bits it hides almost nothing, and at 32 it hides nothing at all.
It is a real trade, not a free tuning knob: either you accept decrypting four times as many rows per query, or the index stays close to bijective. For high cardinality I do not truncate, and for low cardinality I do not use a blind index.
Rotation, where the real cost is
Here is the finding that justifies the article, because it is the one I did not see documented and it is what breaks in production.
With the key version in the row, rotating the encryption key is easy: each record says which key encrypted it, so an old row keeps decrypting with the old key while new writes use the new one. Lazy rotation, no downtime.
With the blind index that does not work. I checked:
── the ciphertext still reads ──
row 0 key_version: 1 · still decrypts: u0@x.com
── but the LOOKUP breaks silently ──
looking up u3@x.com with the v2 index -> 0 rows
The record exists. Its blind index was computed with key 1. The application now searches with key 2. No exception, no error: zero rows. The user sees “not found” for data that is sitting right there, and that can run for months before anybody connects it to the rotation.
The reason is structural. The ciphertext carries its version inside it, so it can be decrypted with the right key. The blind index is the search criterion: to find it you would have to know its version before finding it.
The way out is to search across every live version:
WHERE tenant_id = $1 AND email_bidx IN ($2, $3, ...)
And its cost, measured:
1 live version -> Index Searches: 1 · Buffers: 4
2 versions -> Index Searches: 2 · Buffers: 7
3 versions -> Index Searches: 3 · Buffers: 10
5 versions -> Index Searches: 5 · Buffers: 16
Linear, and in absolute time irrelevant at this scale. But the design consequence is not: the IN grows with every rotation and never shrinks on its own. Either you recompute every blind index in the table — a batched migration with dual writes while it runs — or you carry a query that degrades with each rotation.
My practical conclusion: the blind index key and the encryption key must be separate keys with separate rotation policies. The encryption key rotates lazily and undramatically. The blind index key rotates rarely, is planned as a migration, and gets a date attached from day one.
All of the above measured on PostgreSQL 18.4 over 300,000 rows, with cryptography 48.0.0 and Python 3.12.10.
Which fields deserve this
The decision I have most often seen made badly. My criteria:
| You need | High cardinality | Low cardinality |
|---|---|---|
| Only to read the value | Encrypt, no index | Encrypt, no index |
| Equality lookup | Blind index | Reconsider: it leaks too much |
| Uniqueness | Unique blind index | Not applicable |
| Ordering or ranges | Not possible: redesign | Not possible: redesign |
| Prefix or free text | Not possible with this technique | — |
And one recommendation that runs against instinct: do not encrypt the status field. It is low cardinality, it leaks its whole distribution, and it is almost never the sensitive datum. Encrypt the name, the ID number, the address and the diagnosis; leave status in the clear and protect it with isolation and access control, which is what those are for.
When not to
If your threat is a stolen laptop or a lost backup, disk encryption covers you and this is overhead with a permanent operational cost.
And if the field is constantly queried by a reporting process that needs aggregates, sorting and ranges, field-level encryption will turn that report into a problem a blind index does not solve. There the conversation is not technical: it is deciding whether that report can live with aggregated or pseudonymized data instead of the real thing.
Closing
The blind index is one of those techniques that look like a trick and are a trade. You get back equality and uniqueness, you lose ordering and prefix for good, and you take on three costs: normalizing yourself, leaking structure on low-cardinality fields, and a rotation that is no longer lazy.
Of the three, the one you pay late is the last. Encryption gets designed on day one; rotation is needed the day a key is compromised, or the day a contract demands it every twelve months. If that is the day you discover that rotating the blind index means silent zero-row results in production, the conversation is very different from one where it was planned from the start.
So when I sign off a design like this, the question is not whether the encryption is correct. It is:
How long does your system take to rotate a compromised key, and what breaks without raising an error while it does?