TechBuzzPro

Field-Level Encryption Without Losing Search and Sort

· 6 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Field-level encryption protects sensitive data—like email addresses, phone numbers, or national IDs—so that even if your database is compromised, the plaintext values stay unreadable. The classic problem is that encrypted data can't be searched or sorted normally. This guide shows you how to keep your data encrypted at the field level while still supporting exact-match lookups, partial searches, and sorting, using techniques like deterministic encryption, blind indexes, and searchable encryption.

What You'll Need

  • A database that supports indexes (most relational and NoSQL databases do).
  • An application layer (backend) where you can add encryption logic—ideally before data is written to the database.
  • A key management system (KMS) or a secure way to store and rotate encryption keys. This could be a cloud KMS (AWS KMS, Azure Key Vault, GCP KMS) or a hardware security module (HSM).
  • Access to your database schema to add new columns or tables.
  • A basic understanding of your application's data access patterns (which queries you run against the sensitive fields).

Step-by-Step

  1. Identify the fields that truly need encryption. Not all data needs field-level encryption. Focus on high-risk fields like personal identifiers, financial data, health records, or authentication tokens. Over-encrypting can hurt performance and complicate development.
  2. Choose an encryption scheme. For searchable and sortable encryption, you have three main options:
    • Deterministic encryption: The same plaintext always produces the same ciphertext. This allows exact-match searches and equality-based sorting, but it leaks whether two records have the same value. Use it for fields where that leak is acceptable (e.g., a country code).
    • Blind indexing: You store a separate, derivable value (like a hash or HMAC) alongside the encrypted data. The blind index is used for lookups, while the actual data is encrypted with a random IV (initialization vector), so it's more secure than deterministic encryption. Sorting on the blind index is possible if the index preserves order (e.g., a reversible format-preserving encryption).
    • Searchable encryption (e.g., OPE - Order-Preserving Encryption): This encrypts data in a way that preserves the numerical or lexicographical order. It allows range queries and sorting directly on the ciphertext, but it's more complex and can leak order information. Use it only when you absolutely need range queries.
  3. Design your database schema. For each encrypted field, you'll likely need:
    • The encrypted value itself (store as a binary or string column).
    • One or more blind index columns (e.g., a hash of the plaintext for exact lookups, or a truncated hash for prefix searches).
    • If you need sorting, an additional column that stores a sortable encrypted value (e.g., using OPE or a separate sortable token).
  4. Implement encryption logic in your application. Write functions that encrypt and decrypt data using your chosen KMS or local keys. Ensure that encryption happens before data is written to the database, and decryption happens only after reading. Never store plaintext in logs or backups.
  5. Create the blind index. For exact-match searches, compute a deterministic hash (like SHA-256) of the plaintext and store it in a separate column. For partial searches (e.g., LIKE '%john%'), you can store a set of n-grams (substrings) as blind indexes. For sorting, you might use a format-preserving encryption that preserves order, or store a separate sortable token.
  6. Update your queries. Instead of querying the encrypted column directly, query the blind index column for equality or prefix matches. For sorting, use the sortable token column. For example, instead of WHERE email = 'user@example.com', you'd run WHERE email_hash = HASH('user@example.com').
  7. Handle decryption at the application level. After fetching rows, decrypt the sensitive fields in memory before returning them to the client. Never decrypt in the database layer unless you're using a database that supports encryption functions (and even then, it's often better to keep keys out of the DB).
  8. Test thoroughly. Verify that exact-match searches return the correct rows, that partial searches work as expected (if you implemented n-grams), and that sorting produces the correct order. Also test edge cases like empty strings, null values, and special characters.
  9. Plan for key rotation. When you rotate encryption keys, you'll need to re-encrypt all data. This can be done offline or in batches. Ensure your application can handle a mix of old and new keys during the transition.
  10. Monitor performance. Blind indexes and additional columns can slow down writes and increase storage. Monitor query performance and adjust indexes as needed.

Common Mistakes

  • Using deterministic encryption for everything: It leaks equality information, which can be a privacy risk. Use it only when the leak is acceptable.
  • Forgetting to hash the blind index: If you store the plaintext in a blind index column without hashing, you've defeated the purpose. Always use a cryptographic hash or HMAC.
  • Storing the encryption key in the database: This is a critical vulnerability. Keys should be in a separate KMS or environment variable, never in the same database as the encrypted data.
  • Not handling null values: Encrypting a null value can produce a different ciphertext each time, breaking equality searches. Decide how to handle nulls (e.g., store a constant hash for null).
  • Ignoring case sensitivity: If you search for emails case-insensitively, you need to normalize the plaintext (e.g., lowercase) before hashing, otherwise the hash won't match.
  • Over-encrypting fields: Encrypting fields that don't need it adds complexity and performance overhead without benefit.

Tips

  • Use a well-vetted library: Don't roll your own crypto. Use libraries like AWS Encryption SDK, Google Tink, or libsodium.
  • Separate blind indexes from encrypted data: Keep the blind index in a separate column or even a separate table to reduce the risk of correlation attacks.
  • Consider using a database that supports encryption natively: Some databases (like MongoDB Enterprise or SQL Server) offer field-level encryption with searchable capabilities. This can save development time.
  • Test with realistic data volumes: Performance issues often appear only with large datasets. Load test your queries.
  • Document your encryption scheme: Future developers need to know how to add new fields or change the scheme.
  • Use a separate key for each field or tenant: This limits the blast radius if one key is compromised.

Troubleshooting

  • Search returns no results: Check that the blind index is computed correctly. Ensure you're using the same hash function and normalization (e.g., lowercase) in both the write and read paths.
  • Sort order is wrong: If you're using a blind index for sorting, it must preserve the original order. Consider using OPE or a separate sortable token. Verify the collation of the column.
  • Decryption fails: This usually means the key is wrong or the data was encrypted with a different key. Check your key management and ensure you're using the correct key version.
  • Performance is slow: Indexes on blind index columns can help, but they may not be used if the query isn't sargable. Use EXPLAIN to see if the index is being used. Consider adding a composite index.
  • Null values cause issues: Decide on a consistent representation for null (e.g., a constant hash) and handle it in your encryption/decryption functions.
  • Data migration is painful: Write a migration script that reads plaintext, encrypts it, and populates the blind index columns. Test on a copy of the production data first.

Frequently Asked Questions

  • Can I use the same key for all fields? Yes, but it's better to use separate keys per field or per tenant to limit exposure. Key rotation becomes more granular.
  • Does field-level encryption work with existing queries? No, you'll need to modify queries to use blind indexes or searchable encryption. This is a significant refactor.
  • What is the performance overhead? Encryption/decryption adds CPU time, and blind indexes add storage. Queries on blind indexes are usually fast if indexed properly, but writes become slower.
  • Can I do range queries (e.g., age > 30)? Yes, but you need order-preserving encryption (OPE) or a separate sortable token. OPE is complex and can leak order information, so use it cautiously.
  • Is deterministic encryption safe? It's safe if the data is not sensitive to equality leakage. For example, encrypting a country code might be fine, but encrypting an email address is not, because the same email would produce the same ciphertext, allowing an attacker to infer relationships.
  • How do I rotate keys? Decrypt all data with the old key, re-encrypt with the new key, and update the blind indexes. This should be done in a controlled maintenance window.