読み物Application Security · Privacy

Level: Pro

Privacy Engineering: Encryption, Retention, Deletion, and Data Protection

Turn privacy principles into code: encryption that fits the threat, field-level encryption with authenticated ciphers, pseudonymization, retention jobs, deletion that reaches backups, and breach readiness.

Edeeson Opina10 min read

A Pro lesson card: lesson 14 of the Security & Privacy series, Privacy Engineering: Encryption, Retention, Deletion, and Data Protection, with the Miso fox waving.

What you’ll learn

  • Choose between disk, database, and field-level encryption by threat
  • Encrypt a field correctly with AES-256-GCM and managed keys
  • Pseudonymize identifiers with keyed hashes
  • Implement retention and deletion, including backups and processors
  • Prepare for breach notification duties
On this page
  1. Before you start
  2. The data lifecycle
  3. Choosing encryption by threat
  4. Encrypting a field correctly
  5. Key management
  6. Crypto-shredding
  7. Pseudonymization
  8. Retention and deletion
  9. Breach readiness
  10. Common mistakes and troubleshooting
  11. Practical exercise: protect one sensitive field
  12. Key takeaways
  13. References
  14. What's next

Privacy principles such as purpose limitation and proportionality only protect people when they become working code: data that's encrypted where the threat demands it, identifiers that can't be linked without a key, records that are actually deleted when their time is up, and a team ready to act when something leaks. This lesson is about that engineering. It covers choosing the right kind of encryption, encrypting a field correctly with authenticated encryption and managed keys, pseudonymization, retention and deletion that reach backups and processors, and preparing for breach notification duties.

Before you start

Read Understanding Personal Data, Privacy, and Data Minimization for the principles and the data inventory, and Threat Modeling and Secure-by-Design Software Architecture for how to reason about threats. Examples use Node.js with TypeScript, PostgreSQL, and Prisma. The legal points use the EU's GDPR as an example and aren't legal advice.

The data lifecycle

Personal data passes through stages, and each one needs its own controls:

  1. Collect only what a stated purpose needs, with notice.
  2. Store it encrypted where appropriate, with access limited to the roles that need it.
  3. Use it only for the purpose it was collected for.
  4. Share it only with processors and partners under agreements, and only the fields they need.
  5. Retain it for a defined period tied to the purpose or a legal duty.
  6. Delete it at the end of that period, including copies in backups, logs, caches, and processors.

Most privacy failures happen at the edges of this cycle: data collected without a purpose, shared more widely than intended, or kept long after anyone needed it. Your data inventory from lesson 4 should record each stage for each kind of data.

Choosing encryption by threat

"Encrypt the data" means little until you ask: encrypt against whom? Different layers stop different threats.

  • Encryption in transit (TLS) stops people on the network. Use it for every connection, including between your application and the database.
  • Disk or volume encryption stops someone who steals a physical disk or an unattached cloud volume or snapshot. Most cloud providers enable it by default. It doesn't help when the running server or database is compromised, because the data is decrypted for anyone with access.
  • Database-level encryption (transparent data encryption) is similar: it protects files and backups at rest, not data queried through a compromised application.
  • Field-level (application-level) encryption encrypts specific values in your application before they reach the database. A database dump, a read replica, a backup, or a database administrator sees only ciphertext. It protects against database and backup leaks, but not against a compromise of the application that holds the key.

Field-level encryption has real costs: you can't search, sort, or index encrypted values normally, and key management becomes your problem. Use it for high-impact fields such as government ID numbers, health information, or bank details, not for every column.

Encrypting a field correctly

Use an authenticated encryption mode, which provides both confidentiality and integrity: any tampering with the ciphertext is detected on decryption. AES-256-GCM is widely available and a good default. Its rules are strict:

  • Use a key of 32 random bytes from a secure source, never derived from a password without a key derivation function.
  • Use a fresh, random 12-byte IV (nonce) for every encryption with the same key. Reusing an IV with the same key in GCM is catastrophic: it can reveal plaintext and let an attacker forge messages.
  • Store the IV and the authentication tag with the ciphertext; they aren't secret.
  • Use additional authenticated data (AAD) to bind the ciphertext to its context, such as the record ID and field name, so an attacker with database access can't swap encrypted values between rows.
field-crypto.tsTypeScript
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";

const VERSION = "v1";

/** Encrypts one field value. The key is 32 bytes; context binds the ciphertext to a record and field. */
export function encryptField(plaintext: string, key: Buffer, context: string): string {
  const iv = randomBytes(12); // never reuse an IV with the same key
  const cipher = createCipheriv("aes-256-gcm", key, iv);
  cipher.setAAD(Buffer.from(context, "utf8"));
  const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const tag = cipher.getAuthTag();
  return [VERSION, iv.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(".");
}

export function decryptField(stored: string, key: Buffer, context: string): string {
  const [version, iv, tag, ciphertext] = stored.split(".");
  if (version !== VERSION || !iv || !tag || !ciphertext) throw new Error("Unknown ciphertext format");
  const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64url"));
  decipher.setAAD(Buffer.from(context, "utf8"));
  decipher.setAuthTag(Buffer.from(tag, "base64url"));
  // final() throws if the ciphertext, tag, or context was altered
  return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64url")), decipher.final()]).toString("utf8");
}

// Usage: the context ties the value to one user's tax ID field.
// const stored = encryptField(taxId, dataKey, `user:${user.id}:taxId`);

The version prefix lets you change algorithms or keys later without guessing how old values were encrypted. Write tests that prove decryption fails when the ciphertext, tag, or context is changed:

field-crypto.test.tsTypeScript
import { randomBytes } from "node:crypto";
import { expect, it } from "vitest";
import { decryptField, encryptField } from "./field-crypto";

const key = randomBytes(32);

it("round-trips and rejects tampering or a different context", () => {
  const stored = encryptField("123-456-789", key, "user:42:taxId");
  expect(decryptField(stored, key, "user:42:taxId")).toBe("123-456-789");
  expect(() => decryptField(stored, key, "user:43:taxId")).toThrow();
  const [v, iv, tag, data] = stored.split(".");
  const flipped = Buffer.from(data!, "base64url");
  flipped[0] = flipped[0]! ^ 1;
  expect(() => decryptField([v, iv, tag, flipped.toString("base64url")].join("."), key, "user:42:taxId")).toThrow();
});

it("uses a different IV each time", () => {
  expect(encryptField("same", key, "c")).not.toBe(encryptField("same", key, "c"));
});

Don't design your own cryptographic constructions beyond this. If you need more, such as searchable encryption or many keys with rotation, use a vetted library or your cloud provider's encryption SDK.

Key management

Encryption moves the problem from protecting data to protecting keys. A key stored next to the data, or in the same database, or in the source code, protects very little.

  • Keep keys in a key management service (KMS) or hardware security module, not in the database or code.
  • Use envelope encryption: the KMS holds a key-encryption key that never leaves it; your application asks the KMS to generate and wrap a data key, uses the data key in memory to encrypt fields, and stores only the wrapped data key. Decrypting requires a KMS call that is access-controlled and logged.
  • Separate duties: the people and systems that can read the database shouldn't automatically be able to use the KMS key.
  • Plan rotation: store a key ID or version with each ciphertext, encrypt new data with the new key, and re-encrypt old data in the background.

Crypto-shredding

If each user's data is encrypted with its own data key, destroying that key makes the data unreadable everywhere it exists, including in backups you can't edit. This technique, called crypto-shredding, is a practical way to make deletion reach immutable copies. It only works if the key itself isn't also kept in the backups.

Pseudonymization

Sometimes you need to link records about the same person, for analytics or abuse detection, without knowing who they are. Pseudonymization replaces identifiers with values that can't be traced back without separate information. A plain hash of an email address isn't enough: anyone can hash a list of known emails and match them. Use a keyed hash (HMAC) with a secret key kept apart from the data:

pseudonym.tsTypeScript
import { createHmac } from "node:crypto";

/** Stable pseudonym for joining records; reversible only by someone holding the key and a list of candidates. */
export function pseudonymize(identifier: string, key: Buffer): string {
  return createHmac("sha256", key).update(identifier.trim().toLowerCase()).digest("base64url");
}

Pseudonymized data is still personal data under most laws, because whoever holds the key can re-identify people. Anonymization, in contrast, means re-identification is no longer reasonably possible by anyone, which is much harder to achieve than it looks. Combinations of quasi-identifiers such as birth date, postcode, and gender identify most people, so aggregate, generalize, or add noise before calling data anonymous.

Retention and deletion

A retention period is only real if code enforces it. For each kind of data in your inventory, decide the period and the trigger (for example, "support tickets: two years after closing"), then implement a scheduled job:

retention-job.tsTypeScript
// Runs daily. Deletes in batches so it never locks large tables for long.
export async function applyRetention(now = new Date()) {
  const cutoff = new Date(now.getTime() - 730 * 24 * 3600_000); // two years
  let deleted = 0;
  for (;;) {
    const batch = await db.supportTicket.findMany({
      where: { closedAt: { lt: cutoff }, legalHold: false },
      select: { id: true },
      take: 500,
    });
    if (batch.length === 0) break;
    const result = await db.supportTicket.deleteMany({ where: { id: { in: batch.map((ticket) => ticket.id) } } });
    deleted += result.count;
  }
  logger.info({ event: "retention.support_tickets", deleted }); // counts only, no content
}

Deletion has to reach every copy:

  • Related tables and files: attachments in object storage, search indexes, and caches. Use foreign keys with cascading deletes where appropriate, and delete files explicitly.
  • Logs and analytics: give them their own, shorter retention periods.
  • Backups: you usually can't edit them, so keep their retention short and documented (for example, 35 days), make sure restores re-apply deletions, or use crypto-shredding.
  • Processors: email providers, analytics vendors, and support tools hold copies. Use their deletion APIs or settings, and check retention terms in your agreements.

Support data subject rights the same way: an export of what you hold about a person, built from your inventory, and a deletion that follows the same paths. Under the GDPR, people have rights including to be informed, to access, to correct, to erasure in certain circumstances, and to data portability; other laws have similar rights with different conditions.

Breach readiness

Despite your efforts, plan for a personal data breach. Laws impose deadlines that are hard to meet without preparation:

  • Under the EU GDPR (Article 33), controllers must generally notify the supervisory authority within 72 hours of becoming aware of a personal data breach, unless it's unlikely to result in a risk to people's rights and freedoms. When the risk to people is high, Article 34 also requires telling the affected people without undue delay.
  • Many other countries' laws and sector rules set their own deadlines, thresholds, and notification contents, and some are shorter. Find out which apply to you before an incident, not during one.

Engineering makes these deadlines achievable. Know what data each system holds (your inventory), keep audit logs that show what was accessed, be able to identify affected people quickly, and have the incident response plan from lesson 15 ready. Encryption with well-protected keys can also reduce harm, and some rules take it into account when assessing the risk of a breach.

Common mistakes and troubleshooting

  • Assuming disk encryption protects against application compromise. It doesn't; data is decrypted for the running system.
  • Reusing GCM IVs or using a fixed IV. Generate a random 12-byte IV for every encryption.
  • Unauthenticated modes such as AES-CBC without a MAC. Use authenticated encryption.
  • Keys in the same database or repository as the data. Use a KMS and envelope encryption.
  • Plain hashes as pseudonyms. Use HMAC with a separate secret key.
  • Retention periods in a policy but not in code. Implement and monitor the jobs.
  • Forgetting backups and processors in deletion. List every copy in your inventory.

If decryption starts failing after a deployment, check that the key ID matches, the context string is built exactly as before (including field names and casing), and the ciphertext column wasn't truncated by a length limit.

Practical exercise: protect one sensitive field

In a local practice project:

  1. Pick one high-impact field, such as a government ID, and encrypt it with encryptField using a key loaded from configuration (in production, from a KMS).
  2. Bind the context to the record ID and field name, and run the tamper tests.
  3. Replace an analytics user ID with an HMAC pseudonym.
  4. Add a retention job for one table, with a test that seeds old and new records and checks only the old ones are deleted.
  5. Extend your data inventory with the encryption, retention, and deletion path for each field, including backups and processors.

Key takeaways

  • Pick encryption by threat: TLS for networks, disk encryption for stolen media, field-level encryption for database and backup leaks.
  • Use AES-256-GCM with a random IV per encryption, AAD for context, and keys held in a KMS with envelope encryption.
  • Pseudonymize with keyed hashes; pseudonymized data is still personal data.
  • Enforce retention in code, and make deletion reach related records, logs, backups, and processors.
  • Prepare for 72-hour breach notification duties before you need them.

References

What's next

The final lesson brings everything together in production. Production Security: Testing, Monitoring, and Incident Response covers the tests, logs, alerts, and practiced response that keep an application secure after launch.

See every lesson in Security & Privacy: Building Secure Applications