Searchable Encrypted Chat in PostgreSQL
This architecture allows keyword search over encrypted chat messages without storing message plaintext or query terms in the database. It has two parts:
The server holds the keys, so this is encryption at rest, not end-to-end encryption.
Run the demonstration on GitHub →1. Threat Model
Target: protection against offline database compromises (stolen backups, leaked snapshots, or read-only SQL injection).
Assumption: the attacker has full access to the database tables, but no access to application server memory or to the master key file.
Scope: this is not end-to-end encryption (E2EE). The application server holds the keys in memory to handle search, previews, and history sync. Whoever controls the application server can read messages.
2. Key Architecture
Every chat uses two distinct 256-bit keys:
[ Master Key ] (file secret on the application server; never written to the DB)
│
├─ Wrapped Message Key ──► stored in DB (bound to chat_id + purpose + version)
└─ Wrapped Search Key ──► stored in DB (bound to chat_id + purpose + version)
Storage: both keys are stored in the database, wrapped (encrypted) by an application-level master key.
Context binding: key wrapping includes authenticated data: chat id, key purpose, and key version. A wrapped key cannot be moved to another chat or swapped between the search and message roles.
Rotation:
Memory lifecycle: unwrapped keys live only in a bounded in-memory cache, and a key is dropped 10 minutes after its last use. They are never written to logs, the database, or Redis.
CREATE TABLE dm_chat_keys (
chat_id bigint NOT NULL REFERENCES dm_chats (id) ON DELETE CASCADE,
purpose smallint NOT NULL CHECK (purpose IN (1, 2)), -- 1 message, 2 search
key_version integer NOT NULL CHECK (key_version >= 1),
wrapped_key bytea NOT NULL,
created_at timestamp NOT NULL DEFAULT now(),
retired_at timestamp,
PRIMARY KEY (chat_id, purpose, key_version)
);
CREATE UNIQUE INDEX dm_chat_keys_one_active
ON dm_chat_keys (chat_id, purpose) WHERE retired_at IS NULL;
The partial unique index lets the database enforce the rule that matters: a chat has exactly one active key per purpose. A rotated message key is marked retired, not deleted, so older messages still decrypt with the version they name.
3. Message Encryption
Messages are encrypted with AES-256-GCM, with a fresh random 12-byte initialization vector (IV) for every write.
Payload structure
Stored in the message row as a single binary blob:
[ Format (1B) ] [ Key Version (4B) ] [ IV (12B) ] [ Ciphertext + Auth Tag (16B) ]
Additional Authenticated Data (AAD)
Constructed at runtime and fed into AES-GCM verification; not stored in the database:
[ Format (1B) ] [ Key Version (4B) ] [ Part (1B) ] [ Chat ID (8B) ] [ Message ID (8B) ] [ Sender ID (8B) ]
The AAD enforces cryptographic integrity:
In Java
The AAD is 30 bytes, built in the same order every time. The part byte is 1 for the message body and 2 for its preview.
static final byte FORMAT_V1 = 1;
static final byte PART_CONTENT = 1;
static final byte PART_PREVIEW = 2;
static byte[] aad(byte format, int keyVersion, byte part, long chatId, long messageId, long senderId) {
return ByteBuffer.allocate(1 + 4 + 1 + 8 + 8 + 8)
.put(format)
.putInt(keyVersion)
.put(part)
.putLong(chatId)
.putLong(messageId)
.putLong(senderId)
.array();
}
// In the encrypt method:
byte[] iv = new byte[12];
secureRandom.nextBytes(iv); // fresh for every encryption
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, messageKey, new GCMParameterSpec(128, iv));
cipher.updateAAD(aad(FORMAT_V1, keyVersion, PART_CONTENT, chatId, messageId, senderId));
byte[] ciphertext = cipher.doFinal(plaintext); // ciphertext followed by the 16-byte tag
// Stored: format | keyVersion | iv | ciphertext
Decryption rebuilds the same AAD from the row it is reading. If any of those values differ from the ones used at encryption, doFinal throws and nothing is returned.
4. The Blind Index
Because AES-GCM produces different ciphertext for every write, standard database indexes cannot locate recurring words. Search requires a deterministic representation of terms that does not expose the underlying text.
Token generation
When a message is saved, the server normalizes the text (extracts words of 3 characters or more, strips stopwords) and hashes each distinct word:
token = 24 bits of HMAC-SHA256( search key, "escodes/dm-search/v1\0" ∥ word )
The result is an integer from 0 to 16,777,215, stored in its own table:
CREATE TABLE dm_message_search (
chat_id bigint NOT NULL,
token integer NOT NULL,
msg_id bigint NOT NULL REFERENCES dm_messages (msg_id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, token, msg_id)
);
CREATE INDEX dm_message_search_msg_idx ON dm_message_search (msg_id);
The primary key is the search index: a lookup by chat and token is a plain B-tree scan, and no second index is needed for it. Deleting a message deletes its tokens with it, so nothing about a removed message stays behind in the index.
In Java
The first four bytes of the digest are read as an integer, and a mask keeps its low 24 bits.
static final int TOKEN_BITS = 24;
static final int TOKEN_MASK = (1 << TOKEN_BITS) - 1;
static final byte[] DOMAIN = "escodes/dm-search/v1\0".getBytes(StandardCharsets.US_ASCII);
static int token(SecretKey searchKey, String word) throws GeneralSecurityException {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(searchKey.getEncoded(), "HmacSHA256"));
mac.update(DOMAIN);
byte[] digest = mac.doFinal(word.getBytes(StandardCharsets.UTF_8));
// 0 to 16,777,215
return ByteBuffer.wrap(digest, 0, Integer.BYTES).getInt() & TOKEN_MASK;
}
Design controls
5. Query Execution Pipeline
Search is executed in two stages to limit decryption operations:
[ User Query ]
│
▼
1. Normalize query terms -> generate 24-bit tokens per readable chat
│
▼
2. SQL query: match integer tokens in DB (filtered by authorized chat IDs)
│
▼
3. DB returns candidate message IDs (ranked by token overlap + recency)
│
▼
4. App server decrypts candidates in memory (batches of 40)
├─ Discard collision false positives
└─ Build highlighted snippets from verified text
│
▼
[ Return 1 page of results ]
Query privacy: queries are sent in the HTTP POST body (avoiding URL access logs) and are never written to the database or to logs.
6. Information Leakage Matrix
| Data point | Leaked in DB dump? | Details |
|---|---|---|
| Message text and previews | No | AES-256-GCM encrypted. |
| Search queries | No | Ephemeral, memory-only. |
| Cross-chat word links | No | Blocked by isolated per-chat search keys. |
| Token-to-word mappings | No | Computing any token requires the chat’s search key. |
| Shared tokens within a chat | Yes | Shows that two messages in the same chat probably share a word. |
| Word frequency within a chat | Yes | A high-frequency token indicates a repeated word in that chat. |
| Distinct word count per message | Yes | Reflected by the count of token rows per message. |
| Metadata | Yes | Senders, recipients, timestamps, and message sizes are unencrypted. |
The index leak is confined to one chat, and it says “these messages share something”, not what. The only person who could map tokens back to words is someone who already knows what was said in that chat, which means a member, who can read the messages anyway.
7. Operational Trade-Offs
Search limitations: exact, whole-word matches only. No prefix, suffix, fuzzy matching, or typo tolerance. Words shorter than 3 characters and stopwords are unsearchable.
Write overhead: each distinct word in a message inserts one integer row into the index table.
Search scaling: because search tokens depend on per-chat keys, searching across all of a user’s chats requires calculating HMACs for every chat the user belongs to.
Schema rigidity: changing token bit-depth, normalization rules, or search keys requires a complete reindex of historical messages.
??search.repo.note_en??
Run the demonstration on GitHub →Log in with a ready-made account in one click. Everything resets every three days.