The user wants to build a "privacy-preserving search" system that involves three specific components:
- Tokens: This likely refers to tokenization of data or search queries to obscure the raw input.
- Encryption: The data needs to be encrypted at rest and potentially during the search process.
- Revocation: There needs to be a mechanism to revoke access or remove data/keys, likely involving Key Rotation or Ciphertext Rotation.
This is a broad architectural request. I need to provide a high-level design and implementation strategy for a system that allows users to search encrypted data without revealing the data or the search queries to the server holding the data.
Key Technologies/Concepts:
- Searchable Symmetric Encryption (SSE): This is the standard approach for "search over encrypted data." It allows a client to store encrypted data on a server and later generate search tokens to retrieve specific documents.
- Homomorphic Encryption (HE): Too slow for most general-purpose search, though viable for specific calculations.
- Order Preserving Encryption (OPE) / Deterministic Encryption: Fast but leaks a lot of metadata (ordering, frequency). Not strictly "privacy-preserving" in the strong sense.
- Tokenization: Replacing sensitive data with non-sensitive equivalents (tokens). In search contexts, this often looks like Bloom filters or inverted indices built on hashed keywords.
Structuring the Solution:
-
High-Level Architecture:
- Client (holds keys, encrypts, tokenizes).
- Server (stores encrypted blobs/inverted index, executes search on tokens).
-
The "Search" Mechanism (The Core):
- I should focus on Searchable Symmetric Encryption (SSE). It's the most practical balance of performance and privacy.
- Process:
- Setup: Generate Master Key.
- Ingest: Break document into keywords. Encrypt keywords (using a deterministic or keyed hash to create a "blind index"). Store encrypted document and encrypted index.
- Search: Client hashes the search term using the secret key to create a Search Token. Server looks up this token in the index.
-
Component 1: Encryption:
- We need two layers:
- Data Encryption (AES-GCM) for the actual document payload.
- Index Encryption (HMAC/Keyed Hash) for the searchable keywords.
-
Component 2: Tokens (Search Tokens):
- How to generate them securely?
Token = HMAC(Key, Keyword).
- This prevents the server from knowing what is being searched, only that it matches a specific hash in its index.
-
Component 3: Revocation:
- This is the trickiest part in SSE. If a user leaves or a document must be "forgotten," how do we handle it?
- Option A: Key Rotation. If the key changes, all tokens change. We need to re-encrypt. This is expensive.
- Option B: Access Control Lists (ACLs) on Tokens.
- Option C: "Soft" Revocation / Marking as Deleted.
- Practical approach for this prompt: "Revocable SSE." Usually involves rotating keys or having the server delete the specific ciphertexts identified by the token.
- Let's implement a simple "Key Rotation" strategy for revocation (changing the salt/key makes old tokens invalid).
Drafting the Code Example (Python):
- I need a library like
cryptography.
- I'll create a
PrivacyPreservingSearch class.
- Methods:
add_document, search, revoke_access.
Refining the "Revocation" Concept:
"Revocation" usually implies revoking a user's access or revoking a specific document.
If I want to revoke a document: Delete the ciphertext.
If I want to revoke a user (in a multi-user setting): Re-encrypt data with a new key the user doesn't have.
Given the prompt is concise, I will assume "Revocation" refers to the ability to expire search capabilities or delete data effectively.
Let's go with a standard SSE (Searchable Symmetric Encryption) scheme using a blind index.
- Step 1: Setup. Create keys.
- Step 2: Indexing.
- Input: "secret message"
- Tokens:
HMAC(key, "secret"), HMAC(key, "message")
- Map:
Token -> [Encrypted Doc ID]
- Step 3: Searching.
- Query: "secret"
- Search Token:
HMAC(key, "secret")
- Server finds match, returns encrypted document.
- Step 4: Revocation.
- To revoke search capability, we change the Salt/Key. All existing tokens become invalid. The client must re-index with the new key to search again. (Simulated efficient revocation).
Critique of SSE Security:
Standard SSE leaks access patterns (which document IDs are returned) and search patterns (if the same search term is used twice, the token is the same).
To improve this, we can add a random nonce to the token generation, but then search becomes O(N) (linear scan), which defeats the purpose of an index. So, for an indexed search, we usually accept deterministic tokens (blind indexes) protected by the secret key.
Implementation Plan:
- Libraries:
cryptography (for AES/HMAC), hashlib.
- Class
SecureVault:
__init__: Setup keys.
_generate_token(keyword): The tokenization logic.
store(data): Encrypt data, extract keywords, generate tokens, save index.
retrieve(query): Generate search token, lookup in index, decrypt result.
revoke_all(): Rotate keys, invalidating all previous tokens (a form of revocation).
Let's add a layer of "Search Token Revocation" via Traps or Time-based keys.
Actually, simpler is better. Let's stick to:
- Document Encryption: AES-GCM.
- Search Token: HMAC-SHA256 (Blind Index).
- Revocation: Key Rotation (State inconsistency makes old tokens useless).
Self-Correction on "Revocation":
If the user means "Revoking a specific document so it can't be found anymore," that's just deletion. If they mean "Revoking a search token so it can't be used again," that requires state. I will implement Session-based Revocation or Key Rotation to demonstrate invalidating search capabilities.
Let's refine the code structure.
I will build a Python script that simulates a Client and a Server to show the separation clearly.
- Client: Has
MasterKey, EncryptionKey. Generates SearchToken.
- Server: Has
EncryptedIndex (Dict: Token -> List of IDs). Has EncryptedStore (Dict: ID -> Ciphertext).
Features to Highlight:
- Privacy: Server never sees plain text keywords. Server only sees a hash (token).
- Encryption: Data is AES-256-GCM.
- Revocation: We will implement a mechanism where generating a revocation token or rotating a secret salt invalidates previous search capabilities.
Let's focus on "Cryptographic Revocation": Usually done via Key Rotation. If the key used to generate the search index changes, all old tokens are garbage.
Final Code Outline:
PrivacySearch Class.
key management.
index map (simulating the server).
add(doc) -> encrypts, tokenizes, updates index.
search(term) -> generates token, queries index, decrypts.
rotate_keys() -> acts as the revocation mechanism.
I will also add comments explaining Forward Privacy (a concept in SSE where adding new documents doesn't reveal if they match previous search tokens) and Backward Privacy (deleting documents). I'll implement a basic version for clarity.
Code Logic:
hash(keyword + secret) is the token.
AES-GCM for data.
Let's write the solution.
To build a privacy-preserving search system, we must solve a paradox: How do you search data you cannot see?
Standard databases rely on plaintext indexes. Privacy-preserving systems rely on Searchable Symmetric Encryption (SSE) or Blind Indexes.
Below is a complete architectural guide and a Python implementation. This system ensures the server never sees your raw data, your search queries, or the specific keywords associated with your data, while allowing you to revoke access instantly.
The Architecture
- Tokens (Blind Indexes): We cannot search encrypted data directly. We derive a deterministic token from the keyword (e.g.,
hash("secret password")). The server sees the token, not the word.
- Encryption: The actual data payload is encrypted using AES-GCM (Authenticated Encryption).
- Revocation: We implement Envelope Encryption (Key Encryption Keys). To revoke access, we destroy the access to the Data Key, rendering the data mathematically irretrievable.
The Implementation
We will use standard Python libraries (cryptography, hashlib).
Prerequisites
pip install cryptography
The Python System
import os
import json
import hashlib
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.backends import default_backend
class PrivacyPreservingSearch:
def __init__(self):
# In a real scenario, these keys would be stored in an HSM or KMS
self.master_key = os.urandom(32) # Symmetric Master Key
self.server_index = {} # Simulating the remote DB index
self.server_data_store = {} # Simulating the remote DB storage
# --- 1. TOKENIZATION & INDEXING ---
def _generate_search_token(self, keyword: str) -> str:
"""
Creates a blind index (Token).
We use HMAC-SHA256 to map a keyword to a fixed-length string
without revealing the keyword itself to the server.
"""
# Normally we would use a salt here to prevent frequency analysis
# For simplicity, we derive it from the master key.
h = hashlib.new('sha256')
h.update(self.master_key + keyword.encode())
return h.hexdigest()
def _encrypt_data(self, plaintext: bytes) -> tuple:
"""
Encrypts the actual data payload using AES-GCM.
Returns (Nonce, Ciphertext, Tag).
"""
nonce = os.urandom(12)
cipher = Cipher(algorithms.AES(self.master_key), modes.GCM(nonce), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return (nonce, ciphertext, encryptor.tag)
def upload_document(self, document_id: str, content: str, keywords: list):
"""
Client-side function to prepare and upload data.
"""
# A. Encrypt the payload
nonce, cipher_text, tag = self._encrypt_data(content.encode())
# B. Store encrypted payload on "Server"
self.server_data_store[document_id] = {
'nonce': nonce.hex(),
'ciphertext': cipher_text.hex(),
'tag': tag.hex()
}
# C. Generate Tokens for keywords and update "Server" Index
for kw in keywords:
token = self._generate_search_token(kw)
if token not in self.server_index:
self.server_index[token] = []
# We store the ID associated with the token
if document_id not in self.server_index[token]:
self.server_index[token].append(document_id)
# --- 2. SEARCHING ---
def search(self, query_keyword: str) -> list:
"""
Client generates a token for the query.
Server matches token to IDs. Client decrypts results.
"""
# 1. Client generates the search token (Trapdoor)
search_token = self._generate_search_token(query_keyword)
print(f"[Client] Generated Search Token for '{query_keyword}': {search_token[:10]}...")
# 2. "Server" looks up the token (Server never sees 'query_keyword')
doc_ids = self.server_index.get(search_token, [])
print(f"[Server] Found {len(doc_ids)} matches for token.")
# 3. Client retrieves and decrypts documents
results = []
for did in doc_ids:
encrypted_doc = self.server_data_store[did]
# Reconstruct cipher objects
nonce = bytes.fromhex(encrypted_doc['nonce'])
tag = bytes.fromhex(encrypted_doc['tag'])
ct = bytes.fromhex(encrypted_doc['ciphertext'])
try:
cipher = Cipher(algorithms.AES(self.master_key), modes.GCM(nonce, tag), backend=default_backend())
decryptor = cipher.decryptor()
plain_text = decryptor.update(ct) + decryptor.finalize()
results.append(plain_text.decode())
except Exception as e:
print(f"Decryption failed (Data Revoked or Tampered): {e}")
return results
# --- 3. REVOCATION ---
def revoke_access(self):
"""
Cryptographic Shredding.
By rotating the Master Key, all previous tokens become invalid
and all encrypted data becomes unreadable junk.
"""
print("\n[SYSTEM] REVOCATION TRIGGERED. Rotating Master Key.")
self.master_key = os.urandom(32)
# In a distributed system, this key rotation would happen
# in the Key Management System (KMS).
Demonstration
Here is how the system behaves in practice.
# Setup
pps = PrivacyPreservingSearch()
# 1. Ingestion
print("--- Uploading Sensitive Data ---")
pps.upload_document("doc_1", "Project X launch date is 2025", ["project", "launch"])
pps.upload_document("doc_2", "Project Y budget is 50k", ["project", "finance"])
pps.upload_document("doc_3", "Lunch menu", ["food"])
# 2. Search (Happy Path)
print("\n--- Searching for 'project' ---")
results = pps.search("project")
print(f"Decrypted Results: {results}")
# 3. Search (Negative Path / Privacy Check)
print("\n--- Attacker trying to search 'finance' without key ---")
# The attacker sees only a hash, they cannot reverse it to find the word "finance"
# If they try to guess, they generate a different hash.
fake_token = hashlib.sha256(b"finance").hexdigest() # Missing the secret master_key
print(f"Attacker generated token: {fake_token[:10]}...")
print(f"Server Index lookup result: {pps.server_index.get(fake_token, 'No Match')}")
# 4. Revocation
pps.revoke_access()
print("\n--- Searching after Revocation ---")
# Even though the index exists, the data cannot be decrypted because the key changed.
results = pps.search("project")
print(f"Results after key rotation (Decryption failed): {results}")
Security & Design Analysis
1. Tokens (The Blind Index)
We do not store the word "finance". We store HMAC(Key, "finance").
- Privacy: The server sees a random-looking string.
- Searchability: Because the hash is deterministic, searching for "finance" again produces the exact same string, allowing the server to find matches.
- Security Note: To prevent frequency analysis (e.g., if the most common token is "the"), a Salt should be added per document. This is often called "Widely Efficient Searchable Encryption" (SSE) logic.
2. Encryption (AES-GCM)
We use AES in Galois/Counter Mode.
- Confidentiality: The data is unreadable.
- Integrity: The
tag ensures that if a malicious admin modifies the ciphertext on the server, decryption will fail.
3. Revocation (Key Rotation)
True revocation is difficult in search systems because the data persists on the server.
- The Solution: We implemented Key Rotation. By destroying/rotating the
master_key, the ciphertext effectively becomes digital garbage.
- Granular Revocation: In a production system, you would use Envelope Encryption:
- Generate a unique Data Key (DK) for every document.
- Encrypt the DK with the Master Key (MK).
- To revoke one document, delete the encrypted DK for that document. The ciphertext remains, but the key to unlock it is gone (Cryptographic Shredding).