Encrypting medical records with a per-clinic key: envelope encryption with AWS KMS and AES-256-GCM
Why an encrypted disk is not enough for health data, and how Markmedi encrypts medical records field by field with a per-clinic key protected by AWS KMS.
Almost every cloud provider offers an encrypted disk, encrypted backups and an encrypted bucket at the click of a button. That is real protection, but against one specific kind of attack: someone walking off with the disk or the backup file. If the attacker reaches the database through MySQL itself, with a leaked credential, a forgotten dump or a misconfigured replica, the encrypted disk makes no difference at all. The database hands over the data in plaintext, because that is what it is there for.
In an electronic medical record system, that is the scenario that worries me most. That is why Markmedi encrypts clinical content at the field level, inside the application, with one key per clinic. In this article I explain the model, the format decisions and what changes in day-to-day code.
Three layers
The model has three layers, and none of them replaces the others. The first is transit: TLS on every connection, from the browser to the edge, and from the application to the database, to Redis and to AWS. The second is rest at the infrastructure level: encrypted disks, backups and buckets. The third is the field: the database stores only ciphertext, and reading anything also requires access to AWS KMS.
The third layer is the one that changes the outcome of a database leak. With it, a stolen dump contains ciphertext and encrypted keys, and none of it is any use without KMS.

The envelope
The core idea is envelope encryption, with two levels of keys:
- The master key (CMK) lives in AWS KMS and never leaves it. It does not encrypt data; it only encrypts other keys.
- Each clinic has its own 256-bit data key (DEK). That is the key that encrypts that clinic's medical records.
- The database stores the DEK only in its CMK-encrypted form, in the
clinic_encryption_keystable, along with the key version and its retirement date.
When a request needs to read or write a clinical field, the application reads the clinic's encrypted DEK and asks KMS to decrypt it. The plaintext DEK exists only in the PHP process's memory, for the duration of that request or job, and is discarded at the end. It never goes to Redis, cache, session, logs or the database. KMS is called once per clinic per request; subsequent reads use the key already in memory.

Comparing it with the previous model, where everything depended on Laravel's APP_KEY, shows why it was worth the effort:
Situation | With a single APP_KEY | With per-clinic envelope encryption |
|---|---|---|
The environment file leaks | Every medical record is exposed | Nothing is exposed without KMS access |
The database leaks | Exposed, if the key leaks too | Nothing is exposed without KMS access |
Key rotation | Re-encrypt the entire database | Re-encrypt only the DEKs |
Usage auditing | None | Every Decrypt is logged in CloudTrail |
Incident at one clinic | Affects all of them | Affects only that clinic's key |
AES-256-GCM and associated data
Each field is encrypted with AES-256-GCM, with a fresh random 12-byte IV on every write. GCM produces a 16-byte tag that guarantees integrity: if a single byte of the ciphertext changes, the read fails.
The detail I consider most important is the AAD, the additional authenticated data. Every encryption takes the table, the column, the record id and the clinic id as input. They are not stored in the value, but the tag verifies them. In practice, if someone with database access copies the ciphertext of one medical record into another record, or into a record belonging to another clinic, the tag does not match and the application rejects the value. Without the AAD, encryption would protect confidentiality but leave this kind of swap wide open.

There is one practical catch here: a new record has no id before its first INSERT. The fix is to write the encrypted field after the insert, in the same transaction, or to use an application-generated identifier before writing.
The stored value has a readable header and a base64 body:
mm:v1:k3:<base64(IV + ciphertext + tag)>
│ │ └─ clinic DEK version
│ └──── format version
└──────── Markmedi prefixThe prefix lets me check, with a simple SQL query, whether any value is left outside the format. The key version says which DEK to use on read, which makes rotation possible without downtime. The ciphertext is roughly 35% to 40% larger than the original, so the columns are longText, and columns that used to be JSON no longer are, because ciphertext is not valid JSON.
What changes in the code
For anyone writing code in Markmedi, encryption shows up as an Eloquent cast, ClinicEncrypted, applied to fields holding health data: the content of medical records and their versions, allergies and medications in the clinical profile, consultation transcripts and summaries, and answers to forms and clinical intake sheets.
protected function casts(): array
{
return [
'content' => ClinicEncrypted::class,
'contraindications' => ClinicEncrypted::class,
];
}The consequence is that the database can no longer read these fields. No where, orderBy or LIKE works on them. The few places that filtered by content only wanted to know whether the text was empty, so I created a boolean has_content column, filled in on the model's saving event. The general rule became: every filter we need gets an auxiliary column, boolean or enum, that does not reveal the content.
For exact-match search there is the blind index: a column holding the HMAC-SHA256 of the normalized term, computed with a separate index key that never encrypts data. Searching means computing the HMAC of what the user typed and comparing. The blind index only works for exact matches and must not be used on fields with few possible values, such as sex, because the distribution of the HMACs would reveal the value.
In tests, a FakeKeyProvider replaces KMS and generates local DEKs. No test calls AWS. For every new field there is a test that reads the raw column from the database and checks for the mm: prefix, which stops anyone from adding a clinical field and forgetting the cast.
Files
Clinical photos, exams, consultation audio and generated PDFs live in S3 with SSE-KMS, meaning S3 itself encrypts them with a KMS key dedicated to clinical files. I considered encrypting files in the application and gave up for a practical reason: the audio player requests parts of the file with the Range header, and the pipeline that generates progress videos uses ffmpeg. With application-level encryption, both stop working. With SSE-KMS, they keep working, and reading an object requires kms:Decrypt permission in addition to s3:GetObject. A leaked S3 credential without KMS permission gets AccessDenied. A bucket policy rejects any unencrypted upload.
Rotation
The CMK rotates automatically once a year. KMS keeps the old key material, so nothing needs to be re-encrypted. Rotating a clinic's DEK is on demand: when a leak is suspected, when someone with KMS access leaves, or by policy. The process creates the new DEK (new writes already use the new version), re-encrypts records in batches with a command that can be stopped and resumed, verifies via SQL that no value with the old prefix remains, and only then retires the old key.
There is one rule with no exceptions: a DEK that still encrypts records is never deleted. Brazilian law requires medical records to be kept for 20 years, and a deleted key makes the records unreadable forever.
Side-channel leaks
Field encryption protects the database, and only the database. If the plaintext is copied somewhere else, the protection ends there. That is why the model comes with a checklist I go through on every change:
- Jobs and events receive only IDs, never clinical text as an argument.
SerializesModelsalready helps, because it serializes only the model's key. - Logs record IDs, never the whole model. Before every merge, I search for
Log::andreport(in the changed files. - Error reporting strips the content of exceptions and the request before anything leaves the application.
- No decrypted clinical field goes into the cache.
- PDFs and exports are written only to the clinical bucket, and the temporary file is deleted.
- Email and WhatsApp messages carry a link that requires login, never clinical content.
- Inertia props carry only the fields the screen displays.
A single log line with clinical text undoes everything else. This checklist is what demands the most discipline, which is why a good part of it has been turned into tests.
Migration and recovery
The migration was done in phases that shipped to production separately: first the infrastructure (SSE-KMS on the buckets, TLS on every internal connection), then the has_content column and the filter changes, then the cast and the batch re-encryption, and finally the review of side-channel leaks. During re-encryption, the cast read three formats (the new one, the APP_KEY one and plaintext) and wrote only the new one. Once I confirmed that every value had the prefix, plaintext reading was removed.
Encrypting everything creates a new dependency: without KMS, medical records do not open. If KMS becomes unavailable, scheduling keeps working and only the medical record screen shows a clear message. For the worst case, losing the AWS account, the CMK is multi-region and there is a recovery copy of the DEKs, encrypted with a public key whose private key is kept offline, in a separate backup account. A database backup without the key does not recover clinical text, and I did not want to find that out in the middle of an incident.
Impact in an incident
Scenario | Impact |
|---|---|
Database leak | Low: the attacker has ciphertext and encrypted keys |
Environment file leak | Medium: rotate credentials; the database stays protected without KMS |
Leak of a credential with Decrypt permission | High: disable the credential and rotate the DEKs |
Backup leak | Low, if the backup is encrypted with a key stored outside it |
Legal context
In Brazil, medical records are sensitive personal data under the LGPD, Brazil's data protection law (art. 11), which requires appropriate security measures (art. 46) and notification of incidents to the ANPD, the national data protection authority, and to data subjects (art. 48). Law 13.787/2018 and CFM (Federal Council of Medicine) Resolution 1.821/2007 govern the storage and integrity of electronic medical records, including the 20-year retention period. I used the American HIPAA as a technical reference, because it is detailed about encryption, auditing and integrity, but Markmedi does not present itself as HIPAA certified: that would require specific agreements with every vendor that touches health data.
Encryption does not replace the rest, either: per-clinic and per-role access control, 2FA, session timeout on inactivity and access auditing are still necessary. I cover those layers in Multitenancy and security, and backup and continuity in Lean, resilient infrastructure. The full project is at Markmedi.