Data Protection and Encryption in Practice Questions
Protecting data at rest and in transit across real systems from an engineering rather than pure-cryptography standpoint. Covers encryption strategy and key management for stored and transmitted data, secrets and sensitive-data handling, tokenization and secure elements for payment and sensitive data, and secure data handling in application code. Applied data-protection controls, distinct from cryptographic primitive design and from privacy-regulation compliance.
An analytics platform needs to let analysts run queries on PII without ever exposing plaintext to them. Evaluate secure enclaves, homomorphic encryption, secure multi-party computation, and tokenization or pseudonymization as options. For each, assess feasibility, performance impact, developer effort, and how you would explain the residual risk to a non-technical stakeholder. Recommend a phased implementation.
Sample Answer
Direct answer
None of these options are free: each removes the analysts' access to plaintext through a different mechanism, with very different feasibility, performance, and effort profiles. The practical path for most teams is a phased rollout starting with the cheapest, most mature option, tokenization or pseudonymization, and reserving the more exotic cryptographic techniques for the narrow slice of analysis that genuinely cannot be done any other way.
Structured elaboration
| Option | Feasibility | Performance impact | Developer effort | Residual risk, explained simply |
|---|---|---|---|---|
| Tokenization / pseudonymization | High; mature tooling and patterns | Negligible; a lookup or replace operation, not per-query cryptography | Low to moderate; mostly integration work | Analysts can still see patterns and correlations, just not exact identifiers directly; if enough other columns are present, it is sometimes still possible to identify someone by combining several data points together |
| Secure enclaves (Trusted Execution Environments, TEEs) | Moderate; increasingly available as a cloud confidential-computing option, but the workload usually needs adapting to run inside the enclave | Real but the smallest of the "exotic" options; closer to native speed than homomorphic encryption or secure multi-party computation | Moderate to high; needs infrastructure expertise and a remote-attestation step | Data is briefly decrypted in memory inside hardware-protected isolation, so it relies on trusting the chip manufacturer's guarantees; there is published security research on side-channel attacks (attacks that infer secret data indirectly from measurable effects like timing, power draw, or cache behavior, rather than by breaking the encryption itself) against enclave hardware, so it is strong but not an absolute guarantee |
| Homomorphic encryption (HE) | Low for open-ended, ad hoc analyst querying today; realistically fits only a narrow, pre-defined computation | The heaviest option by far; substantially more expensive per operation than plaintext computation | High; needs specialized cryptography expertise most teams don't have in house | The strongest guarantee on this list, analysts genuinely never see plaintext or even an intermediate decrypted value, but it is currently slow and hard enough to build correctly that it only makes sense for a small number of very high value, well-defined calculations |
| Secure multi-party computation (SMPC / MPC) | Moderate for a specific, well-scoped joint computation between separate organizations; low for one organization's own internal ad hoc analytics | Substantial network and coordination overhead; generally faster than HE for the operations it supports, still far slower than plaintext | High; specialized expertise, fewer production-ready tools than tokenization | No single party sees another party's raw data, only the final agreed result, though a poorly designed protocol or a small result set can sometimes let a party infer more than intended from repeated queries |
Worked example
An honest attestation flow illustrates why a TEE is trusted at all: before releasing any real data or a decryption key into the enclave, a remote verifier requires the enclave to cryptographically prove, through remote attestation, that it is running exactly the expected, unmodified code. Without that step, you are simply trusting an operator's claim that a region of memory is really an untampered enclave, which defeats the purpose. Homomorphic encryption's taxonomy matters for scoping a project correctly: partially homomorphic schemes support one operation, such as only addition, indefinitely; somewhat homomorphic schemes support a limited, bounded number of mixed operations before accumulated noise makes results unusable; fully homomorphic encryption (FHE) supports arbitrary computation through active noise management, at a real and still substantial computational cost, which is why FHE remains largely research and pilot-stage for general analytics today rather than production ad hoc querying.
Recommended phased implementation
- Pseudonymize or tokenize the obvious direct identifiers immediately; this is cheap, mature, and addresses the large majority of the realistic exposure for a small fraction of the engineering cost of the alternatives.
- For the narrow set of analysts or use cases that genuinely need row-level access to sensitive fields, evaluate a TEE-based confidential-computing environment next, since it offers the best balance of cost, effort, and security among the remaining options.
- Reserve homomorphic encryption or secure multi-party computation for one specific, well-justified, narrow computation, for example a single cross-organization aggregate, where the business value clearly outweighs the very high engineering cost, and treat each as its own special project rather than a default architecture choice.
Trade-offs and pitfalls
Teams sometimes reach straight for homomorphic encryption or enclaves because they sound like the strongest possible answer, when tokenization already addresses most of the realistic risk for a much smaller engineering investment. Explaining residual risk honestly to a non-technical stakeholder, especially the re-identification risk that survives tokenization alone, matters more for getting the phasing decision right than picking the most cryptographically impressive option first.
A developer just committed a file containing a plaintext API key to the main repository. Walk through your immediate containment steps, then list at least five long-term controls, both preventive and detective, you would put in place to reduce the risk of this happening again.
Sample Answer
Direct answer
Deleting the file and recommitting does not solve the problem: git history retains every prior commit, so the key is still recoverable by anyone who can clone the repository or has already pulled it. Treat the key as compromised the moment it was pushed to a shared remote, revoke or rotate it immediately at the provider, then work through containment and longer-term controls in that order.
Structured elaboration
Immediate containment steps:
- Revoke or rotate the exposed key at the provider right away, before touching git history. This is the step that actually neutralizes the exposure; rewriting history alone does not, because the key value itself remains valid until revoked.
- Check the provider's usage/audit logs for the key covering the exposure window, to see whether anyone already made unauthorized calls with it.
- Purge the value from git history (for example with
git filter-repoor the BFG Repo-Cleaner) if the old committed value matters for other reasons, understanding this rewrites history and requires a force-push and coordination with every collaborator who has a local clone. - Notify the teams or stakeholders whose systems the key had access to, especially if it had broad scope.
Long-term controls (preventive):
- Pre-commit secret-scanning hooks (for example gitleaks, git-secrets, detect-secrets) that catch a secret before the commit is even created.
- Server-side push protection (GitHub secret scanning push protection or the GitLab equivalent) that blocks the push outright rather than relying on every developer's local hook being installed.
- Short-lived, dynamically issued credentials wherever feasible, so a value that does leak is only useful for minutes rather than indefinitely.
- Least-privilege scoping on every issued credential, so a leak's blast radius is small even when it happens.
- A documented "if you leak a secret" runbook and developer training, so the first instinct is rotate-and-report, not delete-and-recommit.
Long-term controls (detective):
6. Continuous, scheduled full-history repository scanning, catching anything that slipped past commit-time and push-time checks.
7. Provider-side anomaly and usage alerting on the credential itself (unexpected source IPs, unusual call volume).
8. Centralized secrets-manager or credential audit logs correlated into a SIEM (Security Information and Event Management system), so unusual access patterns surface without anyone manually checking logs.
Worked example
A developer commits a .env file containing a live third-party API key and pushes to the shared remote. Within the hour: the key is revoked at the provider and a new one is issued through the team's secrets manager; the provider's usage logs are checked and show no unauthorized calls during the exposure window; the repository history is rewritten with git filter-repo since the same value should never resurface even accidentally, and every collaborator is asked to re-clone rather than merge their stale local history.
Trade-offs and pitfalls
Rewriting shared git history is disruptive (every collaborator must re-clone or rebase), so it is worth doing only when the actual value matters beyond the fact that it once existed; if the key has already been rotated, the primary remaining reason to scrub history is hygiene and audit clarity, not active risk reduction, since the compromised value is no longer valid regardless of whether it's still visible in an old commit.
You maintain ETL jobs that process records containing personally identifiable columns that must be encrypted at rest. Explain how you would implement field-level encryption and decryption in a distributed processing job while minimizing key-access bottlenecks, preserving parallelism, and ensuring only authorized transformations can decrypt specific fields.
Sample Answer
Direct answer: Use envelope encryption with a data key fetched once per batch or partition, not once per record, so parallel workers each hold their own in-memory data key and never bottleneck on a call to the central key service per row, and gate which workers or roles may actually decrypt a field through an explicit authorization check layered on top of the cryptography itself.
Structured elaboration:
Envelope encryption, applied per field. A key management service (KMS) or hardware security module (HSM, a dedicated tamper-resistant device for storing and using keys without ever exposing them in plaintext) holds a key-encryption key, or KEK, that never leaves it. For each batch or partition, request one data-encryption key, or DEK, from the KMS: you get back the plaintext DEK to use locally, plus a KMS-wrapped, encrypted, copy of it to store alongside the encrypted data. Encrypt each field with that in-memory DEK using an AEAD (authenticated encryption with associated data) cipher such as AES-GCM, which both encrypts the value and detects tampering. To decrypt later, in a different job or the same job re-reading its own output, unwrap the stored DEK with one KMS call, then decrypt every field in that batch locally with the recovered plaintext DEK, again without a per-record round trip.
Preserving parallelism and avoiding key-access bottlenecks. Scope one DEK per partition, or per some reasonably-sized batch, so N parallel workers make N key-service calls total for key material, not one per record; most key services enforce a request-rate limit that a per-record call pattern would hit quickly at real scale. Cache the unwrapped DEK in each worker's memory for the life of that partition's processing, and never write the plaintext DEK to disk or pass it between workers over an unencrypted channel. Bind each ciphertext to context that identifies which record it belongs to, additional authenticated data, or AAD, extra context that's authenticated alongside the ciphertext without itself being encrypted, so a ciphertext from one record can't be silently swapped onto another record's row during decryption.
Ensuring only authorized transformations can decrypt. Route decryption through a function that checks the caller's role or identity against an explicit allow-list for that field before ever touching the cryptography, so "has the DEK" and "is allowed to use it for this purpose" are two separate checks, not one. A worker running under a role that doesn't need raw values, a purely structural transformation, or an unrelated analytics job, should be denied even if it technically has access to where the wrapped DEK is stored.
Worked example:
import random
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# NOTE: this demo seeds a plain PRNG so the printed output is reproducible
# on any machine. Real key and nonce generation must use a cryptographically
# secure source (os.urandom / the "secrets" module), never a seeded PRNG.
rng = random.Random(42)
def rand_bytes(n: int) -> bytes:
return bytes(rng.randrange(256) for _ in range(n))
# --- Mock KMS: stands in for a call like AWS KMS GenerateDataKey / GCP KMS
# encrypt. A real client hits the KMS API once per BATCH, not once per row,
# to get a fresh plaintext data key (DEK) plus its KMS-wrapped ciphertext. ---
class MockKMS:
def __init__(self):
self._kek = rand_bytes(32) # the KEK never leaves this "KMS"
kms = MockKMS()
def generate_data_key(kms):
dek = rand_bytes(32)
nonce = rand_bytes(12)
wrapped = AESGCM(kms._kek).encrypt(nonce, dek, None)
return dek, (nonce, wrapped)
def unwrap_data_key(kms, wrapped_blob):
nonce, wrapped = wrapped_blob
return AESGCM(kms._kek).decrypt(nonce, wrapped, None)
def encrypt_field(dek, plaintext: str, aad: bytes) -> tuple:
nonce = rand_bytes(12)
ct = AESGCM(dek).encrypt(nonce, plaintext.encode(), aad)
return nonce, ct
def decrypt_field(dek, nonce, ct, aad, caller_role, allowed_roles):
if caller_role not in allowed_roles:
raise PermissionError(f"role {caller_role!r} is not authorized to decrypt this field")
return AESGCM(dek).decrypt(nonce, ct, aad).decode()
# --- One partition of a distributed job processes many rows. Call the KMS
# ONCE per partition/batch to fetch a data key, cache it in memory for the
# life of the batch, and use it for every row's field-level encrypt/decrypt.
# This is the lever that avoids per-row KMS round trips becoming the
# bottleneck under parallelism. ---
dek, wrapped_dek = generate_data_key(kms)
rows = [
{"user_id": 1, "ssn": "111-22-3333"},
{"user_id": 2, "ssn": "444-55-6666"},
]
encrypted_rows = []
for row in rows:
aad = f"user:{row['user_id']}".encode() # binds ciphertext to its row, blocks swap attacks
nonce, ct = encrypt_field(dek, row["ssn"], aad)
encrypted_rows.append({"user_id": row["user_id"], "ssn_nonce": nonce, "ssn_ct": ct, "aad": aad})
print("Encrypted batch (ciphertext, not the raw SSN):")
for r in encrypted_rows:
print(f" user_id={r['user_id']} ssn_ct={r['ssn_ct'].hex()}")
# Later: a worker running under an "analytics_reader" role tries to decrypt.
recovered_dek = unwrap_data_key(kms, wrapped_dek)
try:
decrypt_field(recovered_dek, encrypted_rows[0]["ssn_nonce"], encrypted_rows[0]["ssn_ct"],
encrypted_rows[0]["aad"], caller_role="analytics_reader", allowed_roles={"pii_processor"})
except PermissionError as e:
print(f"\nDenied as expected: {e}")
# A worker running under "pii_processor" (the authorized transformation) succeeds.
plaintext = decrypt_field(recovered_dek, encrypted_rows[0]["ssn_nonce"], encrypted_rows[0]["ssn_ct"],
encrypted_rows[0]["aad"], caller_role="pii_processor", allowed_roles={"pii_processor"})
print(f"Authorized decrypt for user_id=1: {plaintext}")
Output (the ciphertext bytes are deterministic here only because the demo pins its random source for reproducibility; a real system must use a cryptographically secure random generator, which would make them different on every real run):
Encrypted batch (ciphertext, not the raw SSN):
user_id=1 ssn_ct=7bde620bc1819393323c2ec82f97e15929867177e3a1a0079f12aa
user_id=2 ssn_ct=a98c688646a1a96081a288f0e7b457eb195678bcade24d55bd2883
Denied as expected: role 'analytics_reader' is not authorized to decrypt this field
Authorized decrypt for user_id=1: 111-22-3333
Trade-offs and pitfalls: Choosing a batch size that's too large increases blast radius: if that one DEK is ever compromised, everything encrypted under it in that batch is exposed together, so there's a real trade-off between fewer key-service calls, larger batches, and smaller blast radius per key, smaller batches. Size batches around your actual partition or parallelism unit rather than maximizing one dimension blindly. Also, an authorization check implemented only in application code, with no enforcement at the storage or key-service layer, can be bypassed by anything that gets direct access to the underlying data store.
Describe the envelope encryption pattern used to encrypt large objects in cloud storage: generating a data key, encrypting the data, storing the wrapped data key, and protecting the master key. Explain two benefits of this design and one pitfall it introduces in a multi-service environment.
Sample Answer
Direct answer
Envelope encryption avoids sending large payloads to a key service by using two layers of keys. A Data Encryption Key (DEK), a fresh symmetric key, encrypts the actual data locally. That DEK is then itself encrypted ("wrapped") by a Key Encryption Key (KEK), also called a master key, which lives in a KMS (Key Management Service) or HSM (Hardware Security Module, a tamper-resistant device dedicated to key operations) and never leaves it. The wrapped DEK is stored right alongside the encrypted object; the KEK is never stored next to the data at all.
Structured elaboration
The flow for encrypting an object:
- Request a new DEK from the KMS (or generate one locally and immediately have the KMS wrap it).
- Encrypt the object with the DEK using a fast symmetric cipher (commonly AES-256-GCM), entirely on the local machine.
- Ask the KMS to wrap (encrypt) the DEK using the KEK. The KMS returns the wrapped DEK; it never returns the KEK itself.
- Store the wrapped DEK as metadata next to the encrypted object.
To decrypt later, the caller sends the wrapped DEK back to the KMS, which unwraps it (an operation that requires the caller to be authorized against the KEK's access policy) and returns the plaintext DEK, which is then used locally to decrypt the object.
Worked example (two benefits)
Benefit 1, blast-radius containment: the master key (KEK) never leaves the KMS/HSM boundary, so even if an attacker exfiltrates every encrypted object and every wrapped DEK from storage, none of it is decryptable without also compromising the KMS's own access controls; only the small wrapped DEK, not the master key, is ever "in the open." Benefit 2, throughput: KMS calls are relatively slow and rate-limited (they are a network round trip to a managed service), and most services impose a small maximum payload size for direct encrypt calls. Encrypting a multi-gigabyte object entirely inside the KMS would be impractical; encrypting it locally with a DEK and only sending the small (32-byte) DEK to the KMS to be wrapped keeps the KMS call fast regardless of object size.
Trade-offs and pitfalls
The pitfall in a multi-service environment is key-rotation sprawl: when the KEK is rotated, every previously wrapped DEK still needs to be re-wrapped (or at least remain decryptable) under a key version that the KMS retains, and it's easy for one service's client library to assume only the latest KEK version is ever needed and break on data wrapped under an older version. A second, related failure mode is a per-service KMS key policy quietly diverging from the others, so one service loses the ability to unwrap its own DEKs after an access-control change that looked correct everywhere else.
An application needs to support partial or exact-match search on an encrypted field, for example matching the last four digits of a phone number or looking up a record by an exact value, without exposing the full plaintext. Propose secure design options, and explain what information about the underlying data an attacker could still infer from each approach.
Sample Answer
Direct answer
There is no way to search encrypted data for free: every design that lets you query ciphertext trades away some amount of information to get that capability, and the job is choosing the smallest, most deliberate leak that still meets the actual product requirement.
Structured elaboration
| Approach | How it works | What an attacker can still infer |
|---|---|---|
| Deterministic encryption | Same plaintext always produces the same ciphertext, so an indexed equality lookup works directly | Which rows share a value with each other, and which values are most frequent, via simple frequency analysis |
| HMAC-based blind index | Store a keyed hash (HMAC) of the plaintext alongside randomized ciphertext; search by hashing the query term and matching the stored hash | Same equality and frequency leakage as deterministic encryption, since the HMAC is itself deterministic per key, though the hash key can be rotated somewhat more cheaply since it isn't also the decryption key |
| Deliberate partial exposure (for example last-4-digits search) | Store a low-sensitivity slice of the value in a lightly protected or plaintext column, alongside the full value fully randomized-encrypted separately | Exactly the slice you chose to expose, plus whatever additional narrowing is possible by combining it with other exposed data |
| Order-preserving or bucketed schemes | Ciphertext preserves the relative order of the underlying values, enabling range queries | The relative ordering of every value, which for common real-world distributions (salaries, ages, dates) can often reconstruct values close to exactly, once combined with any public information about the distribution |
| Searchable symmetric encryption (encrypted inverted indexes) | Purpose-built cryptographic schemes for keyword search over ciphertext | Reduced leakage compared to the above, but rarely production-ready outside specialized encrypted-search products; usually not worth the engineering cost for a typical application |
Worked example
Take the specific case in the question: matching the last four digits of a phone number. Store the last four digits in a plain or lightly protected column (a phone number's last four digits have only 10,000 possible values, 10^4, so this is a deliberately small, bounded amount of information to expose) and store the full number separately as randomized ciphertext, unrelated to the last-four column. A search for "ends in 4321" runs a plain WHERE last_four = '4321' query, and the application decrypts the full number only for the small set of matched rows before display. The design is honest about what it gives up: an attacker who sees the last-four column learns exactly that slice, nothing more, and the choice to expose it is deliberate and documented rather than an accident of using deterministic encryption on the whole field.
Trade-offs and pitfalls
The temptation to make more and more fields searchable eventually turns a database that looks encrypted into one that is close to plaintext through the accumulation of leakage channels. Order-preserving encryption in particular looks convenient for range queries but leaks close to as much as the plaintext itself for many distributions, and should be avoided for anything but the least sensitive fields. Restrict searchable or partially exposed fields to the minimum the product genuinely requires, and write down the accepted residual leakage for every one you add, rather than treating "it's encrypted" as the end of the analysis.
Unlock Full Question Bank
Get access to all 22 Data Protection and Encryption in Practice interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.