Skip to main content

Encryption: Data at Rest & In Transit

Encryption is the foundation of PHI protection. This module covers everything from basic cryptographic concepts to production-ready implementations for healthcare applications. Real-world compliance scenario: In 2017, Advocate Medical Group paid 5.55millionafterfourunencryptedlaptopswerestolenfromanadministrativeoffice,exposingtheePHIofapproximately4millionpatients.Hadthoselaptopsusedfulldiskencryptionwithproperkeymanagement,theincidentwouldhavequalifiedforHIPAAsencryptionsafeharborandwouldnothavebeenconsideredareportablebreachatall.Thecostofencryptingthoselaptops?Under5.55 million after four unencrypted laptops were stolen from an administrative office, exposing the ePHI of approximately 4 million patients. Had those laptops used full-disk encryption with proper key management, the incident would have qualified for HIPAA's encryption safe harbor and would not have been considered a reportable breach at all. The cost of encrypting those laptops? Under 200 total. The cost of not encrypting them? $5.55 million in fines, plus years of remediation and reputational damage. Encryption is the single highest-ROI compliance investment you can make.
Learning Objectives:
  • Understand symmetric vs asymmetric encryption
  • Implement AES-256-GCM for data at rest
  • Configure TLS 1.3 for data in transit
  • Design key management systems
  • Implement field-level and database encryption

Why Encryption Matters for HIPAA


Cryptography Fundamentals

Symmetric vs Asymmetric Encryption

Choosing the Right Algorithm


Data at Rest Encryption

Envelope Encryption Pattern

Envelope encryption pattern showing Master Key, DEKs, and PHI data hierarchy

Envelope Encryption Key Hierarchy

The envelope encryption pattern provides multiple layers of protection:
  • Master Key (KEK): Stored in HSM / AWS KMS / HashiCorp Vault
  • Data Encryption Keys (DEKs): Unique per record, stored encrypted
  • PHI Data: Encrypted with the DEK

Implementation with AWS KMS

Field-Level Encryption


Database Encryption

PostgreSQL Transparent Data Encryption (TDE)

MongoDB Client-Side Field-Level Encryption


Data in Transit Encryption

TLS handshake process for secure data in transit

TLS Encryption Handshake

TLS 1.3 Configuration

NGINX TLS Configuration

Certificate Management with Let’s Encrypt


Key Management

HashiCorp Vault Integration

Key Rotation Strategy


Key Takeaways

Encrypt Everything

All PHI must be encrypted at rest and in transit

Use Envelope Encryption

Separate data keys from master keys for security and performance

TLS 1.2+ Required

Never allow older TLS versions or weak ciphers

Manage Keys Properly

Use HSM or Vault; never store keys alongside data

Practice Exercise

1

Set Up Key Management

Deploy HashiCorp Vault or configure AWS KMS for your application.
2

Implement Envelope Encryption

Create an encryption service using the envelope encryption pattern.
3

Configure TLS

Set up TLS 1.3 with proper cipher suites for your API.
4

Encrypt Database

Implement field-level encryption for PHI in your database.
5

Test Key Rotation

Verify that key rotation works without data loss.

Next Steps

E2E Encryption with AI

Learn how to encrypt chat data while using AI agents

Implementation Guide

Put it all together in a production system

Interview Deep-Dive

Strong Answer:
  • Envelope encryption uses a two-tier key hierarchy: a Master Key (KEK) that lives in an HSM or KMS, and Data Encryption Keys (DEKs) that are unique per record or per logical unit of data. The DEK encrypts the actual PHI, and the KEK encrypts the DEK. The encrypted DEK is stored alongside the ciphertext.
  • The reason you do not encrypt everything directly with the master key comes down to three concerns. First, performance: calling out to an HSM or KMS for every encrypt/decrypt operation introduces latency. With envelope encryption, you generate a DEK locally (one KMS call), encrypt potentially megabytes of data with that local key (fast AES operations), then store the encrypted DEK. Decryption reverses this: one KMS call to unwrap the DEK, then local decryption.
  • Second, blast radius: if a single DEK is compromised, only the data encrypted with that specific DEK is at risk. If your master key is compromised, everything is exposed. By generating unique DEKs per patient record or per session, you limit the damage of any single key compromise.
  • Third, key rotation: rotating the master key with envelope encryption is straightforward. You re-wrap all the encrypted DEKs with the new master key (a KMS-side operation that never exposes plaintext DEKs) without re-encrypting the underlying data. Without envelope encryption, rotating a key means decrypting and re-encrypting every single record.
  • In a HIPAA context, this also helps with the safe harbor provision. If your master key in the HSM is never compromised but an encrypted DEK blob leaks, the attacker still cannot decrypt the PHI without access to the KMS.
Follow-up: Your team stores the encrypted DEK in the same database row as the ciphertext. An auditor flags this. Is the auditor right to be concerned?The auditor has a valid concern but the answer is nuanced. Storing the encrypted DEK alongside the ciphertext is actually the standard envelope encryption pattern — AWS KMS documentation explicitly recommends it. The security does not come from separating the encrypted DEK from the ciphertext; it comes from the fact that the encrypted DEK is useless without access to the KMS master key. The real question the auditor should ask is: who has KMS decrypt permissions? If the same database credentials that read the ciphertext also have KMS decrypt access, then an attacker who compromises the database connection effectively has both. The mitigation is IAM separation — the application role that reads from the database should require a separate, tightly scoped KMS policy to decrypt DEKs.
Strong Answer:
  • AES-256-GCM is an authenticated encryption mode — it provides both confidentiality and integrity in a single operation. When you decrypt, GCM verifies that the ciphertext has not been tampered with. If someone flips a bit in the ciphertext, decryption fails with an authentication error.
  • AES-256-CBC provides confidentiality only. It does not tell you whether the ciphertext was modified. This makes it vulnerable to padding oracle attacks: if the application returns different error messages for “invalid padding” versus “invalid data,” an attacker can iteratively recover the plaintext without knowing the key. This is not theoretical — it has been exploited in production systems.
  • CBC also requires careful IV management. The IV must be unique and unpredictable for each encryption operation. If you reuse an IV with the same key, an attacker can XOR two ciphertexts to derive information about the plaintexts. GCM uses a nonce that must be unique but does not need to be unpredictable, and GCM explicitly fails if you accidentally reuse a nonce.
  • For HIPAA compliance, the Security Rule requires integrity controls (Section 164.312(c)(1)). GCM gives you integrity for free. With CBC, you need to add a separate HMAC computation (encrypt-then-MAC), which adds complexity and more opportunities for implementation errors.
Follow-up: You discover a legacy service is using AES-128-ECB to encrypt patient SSNs. How bad is this and what is your remediation plan?This is critical. ECB mode encrypts each block independently, so identical plaintext blocks produce identical ciphertext blocks. For SSNs with predictable patterns, an attacker can build lookup tables or identify patterns without decrypting. Remediation: immediately rotate to AES-256-GCM, re-encrypt all SSNs with the new algorithm, verify the migration with checksums, then purge the old ECB-encrypted values. This should be treated as a security incident — conduct a risk assessment to determine if the ECB-encrypted data was ever exposed, because ECB encryption may not qualify for the HIPAA safe harbor provision.
Strong Answer:
  • The standard approach is blind indexing. For each searchable encrypted field, you compute a deterministic, one-way hash (typically HMAC-SHA256 with a dedicated search key) and store it alongside the encrypted value. To search, you compute the same HMAC of the search input and compare it against the stored hashes.
  • This works because the same plaintext always produces the same HMAC with the same key, enabling exact-match lookups. But the HMAC is not reversible — an attacker who obtains the hash column cannot recover SSNs from it (assuming the HMAC key is secured separately).
  • The tradeoff is that blind indexing only supports exact matches. You cannot do range queries, partial matches, or LIKE searches. For SSNs, exact match is usually sufficient. For names, you might index normalized forms (lowercase, stripped of punctuation).
  • A more advanced approach is deterministic encryption for searchable fields and randomized encryption for non-searchable fields. MongoDB’s Client-Side Field-Level Encryption offers exactly this split.
  • Security implication: deterministic encryption or blind indexes leak equality information. An attacker can tell which records have the same SSN. For high-cardinality fields like SSN this is acceptable, but for low-cardinality fields like gender or blood type, the leakage is significant. Never use deterministic encryption on low-cardinality PHI fields.
Follow-up: A product manager wants fuzzy search on patient names with encrypted data. How would you approach this?This is one of the hardest problems in encrypted search. You could compute and store phonetic hashes (Soundex or Metaphone) of names before encryption, and index those. “Smith” and “Smyth” produce the same Soundex code, enabling phonetic matching. This leaks phonetic equivalence classes, so you need to assess whether that is acceptable for your threat model. Alternatively, decrypt a narrowed result set server-side: first filter by department or date range (unencrypted metadata), then decrypt only those names and apply fuzzy matching in application memory. For more sophisticated approaches, look at searchable encryption schemes, but these have well-documented security tradeoffs and I would want a cryptographer to review the design before deploying it in a HIPAA context.
Strong Answer:
  • Key rotation frequency depends on the key tier. Master keys in an HSM or KMS rotate annually, aligning with NIST guidelines. Data encryption keys rotate every 90 days or after a configurable number of encryptions. Session keys rotate per session or per message.
  • With envelope encryption, master key rotation is a “rewrap” operation: the KMS decrypts each stored DEK with the old master key version and re-encrypts it with the new version. The underlying data is never decrypted or re-encrypted, making master key rotation fast and safe.
  • Old key versions must be retained until all data encrypted under them has been re-wrapped. Never delete a key version while ciphertext encrypted under it still exists. Most KMS systems handle this with key versioning — new encryptions use the latest version, but old versions remain available for decryption.
  • Failure modes to plan for: (1) Incomplete rotation — some DEKs re-wrapped but the process fails partway. Each ciphertext must store which key version encrypted it. (2) Accidental key version deletion renders data permanently unrecoverable. Implement a “minimum decryption version” policy. (3) Rotation during high load — schedule during maintenance windows and make the re-wrap process idempotent and resumable. (4) Every rotation event must be audit logged.
Follow-up: An auditor asks how you would handle actual key compromise — not routine rotation, but a suspected key breach. What changes?Key compromise is fundamentally different. With routine rotation, old data remains readable under old key versions. With compromise, you must assume the attacker can decrypt anything encrypted under the compromised key. The response: immediately generate a new key version and disable the compromised version for encryption. Then launch an emergency re-encryption campaign — not just re-wrapping DEKs, but actually decrypting and re-encrypting the underlying data with new DEKs under the new master key. Simultaneously, trigger your incident response plan: assess what data was at risk, conduct the four-factor breach assessment, and prepare for potential notification obligations. The compromised key’s existence and the timeline of its exposure become forensic evidence.