// notes · security

Encrypting PII columns without losing search

How I encrypted end-user personal data column by column in a multi-tenant Django app, kept exact-match lookups working with a keyed-hash blind index, and what we deliberately gave up.

Why encrypt in the application

The platform is a customer engagement service: each tenant sends email, SMS, WhatsApp and push messages to its own users. That means the database holds a lot of other people's personal data: email addresses, phone numbers, names, device tokens, and the messages themselves.

Disk or volume encryption protects against one threat, a stolen disk. It does nothing for the more likely ones: a database dump that ends up somewhere it should not, a backup copy, or a read-only database login used for reporting. Under India's DPDP Act 2023, any of those would count as a personal data breach.

So the data is encrypted per column, in the application, before it reaches Postgres. A dump, a backup or a read-only login now shows ciphertext.

Two primitives, two keys

1. Randomized encryption for storage

Every sensitive value is stored as a versioned token:

enc:v1:gAAAAABl...   # Fernet: AES-128-CBC + HMAC-SHA256, random IV

Fernet is randomized: the same email encrypts differently every time, so ciphertext reveals nothing about which rows share a value. The enc:v1: prefix does two jobs: it marks a value as already encrypted (so encrypting twice is a no-op) and leaves room for a future format.

The model field decrypts on read, so templates, senders and serializers see plain text and most of the codebase did not change.

2. A blind index for lookups

Randomized encryption makes WHERE email = ? impossible. For the fields that are actually looked up, each table gets a second column with a keyed hash:

def blind_hash(kind, tenant_id, value):
    normalized = normalize(kind, value)          # "" for empty values
    if not normalized:
        return ""
    msg = f"{kind}:{tenant_id}:{normalized}".encode()
    return hmac.new(HASH_KEY, msg, hashlib.sha256).hexdigest()   # 64 hex chars

Equality on the plain value becomes equality on the hash, which is a normal B-tree index lookup, the same shape as the plain index it replaces. Three details matter:

Normalize before hashing

Hashes only match if the inputs match exactly, so every kind is normalized first:

The encrypted column keeps the original spelling, for display and for sending.

What you give up, and how to fail safely

A blind index supports exactly three questions: equals, not equals, and has a value. Everything else is gone for encrypted fields: substring search, contains, ranges, sorting.

That broke real features, and each one needed a decision:

Free-form profile attributes are handled per tenant: each tenant marks which attribute keys hold personal data, and only those values are encrypted and hashed. A tenant cannot mark a key as personal if an existing rule depends on an operator that would stop working.

PII leaks through copies

Encrypting the profile table is the easy part. Personal data also gets copied, and every copy needs its own answer:

CopyTreatment
Message tables (recipient, subject, body, tracked links)Encrypted, with hash columns for the recipient
"Identify" events that update a profileStore that a field changed ("email": "[set]"), never the value; the profile is the only place it lives
Provider error text and journey failuresPartially masked at write time: as****@example.com, +91 98•••••210
Application logsMasked at the call site, plus a log formatter that masks any email or Indian mobile number that slips through, URL-encoded ones included
Idempotency keys that contained a raw push tokenReplaced by a SHA-256 of the token

Partial masking was a deliberate choice over full redaction. Support staff can still tell which recipient an error was about, and failure reasons still group together in reports because the masking is consistent.

Keys

There are two independent keys, both separate from the framework's secret key and from the key that protects stored provider credentials:

Staging and production refuse to start without valid keys. Both come from a secrets manager in the same region as the data (ap-south-1). And one fact went into the restore runbook in bold: losing the encryption keys loses the data. A backup without its keys is ciphertext.

Rolling it out

  1. Add the hash columns and switch the field types. The new field reads a value without the enc:v1: prefix as plain text, so existing rows keep working before anything is encrypted.
  2. Backfill in batches of 1,000 rows: encrypt each value, fill its hash. Already-prefixed values are skipped, so the migration can be re-run safely.
  3. Move the indexes from the plain columns to the hash columns and drop the old ones.

It shipped in four PRs: keys and profiles, per-tenant personal attributes, message tables, and finally the copies, error text and logs.

What it does not cover

Being precise about residual exposure matters more than the encryption itself:

Cost

Small by design. Fernet and HMAC-SHA256 each take microseconds per value. An identify request encrypts a handful of fields; a campaign decrypts one address per recipient while building sends. Hash lookups are B-tree lookups on 64-character columns, the same shape as the plain-text indexes they replaced.

Takeaways