← Back to section · Tutorials & Labs
Where Key Material Belongs: Envelope Encryption, KMS, and the Limits of Environment Variables
What are the risks of putting keys in code, config files, or environment variables? This article explains the layered structure of envelope encryption, the boundary of what a KMS is responsible for, and why environment variables are only a thin last line of defense.
Keys are the most unusual kind of data in an application: unlike business data, they cannot simply be restored from backup when lost, and once one leaks, the historical data it encrypted, the tokens it issued, and the trust relationships it underpinned all fail together. Yet in practice, the most common incidents come from keys being handled like ordinary configuration: hardcoded in source, committed to a repository, baked into a container image, or sitting in a world-readable config file. This article takes apart the ways key material is stored around code: which practices are hard red lines, which are acceptable engineering compromises, and why envelope encryption is the standard isolation layer between long-term keys and large volumes of data.
The red line: no keys in code, repositories, or images
The first rule admits no exceptions: no real-environment master key, private key, or access key may appear in source code, comments, test fixtures, or example configs. The reason is simple — code gets copied to every developer machine, every CI cache, and every browser tab open for a code review, so the exposure surface grows linearly with the number of copies; and repository contents are never truly deleted, surviving in history, forks, and backups. Container images are the same: every layer is a downloadable, unpackable file, so a key passed as a build argument is distributed along with the image.
There are three actionable checkpoints. First, enable secret scanning in the repository, running both before commit and in the pipeline, configured to block rather than merely warn after the fact. Second, example configs contain only placeholders and variable names; real values are always injected from outside. Third, once a key has entered a repository, treat it as leaked: rotate it immediately instead of just deleting that one commit — deleting the record does not recall the copies already made.
Envelope encryption: long-term keys only ever encrypt keys
When data volumes grow, encrypting everything directly with a master key creates two problems: the master key must participate in operations constantly, multiplying exposure opportunities; and rotating it means re-encrypting the entire dataset, at unacceptable cost. Envelope encryption is the standard two-layer structure: for each data object (or batch), generate a random data key and encrypt the data with it; then encrypt that data key with the master key, and store the ciphertext together with the wrapped data key. To decrypt, unwrap the data key with the master key first, then decrypt the data with the data key.
This structure brings three engineering benefits. First, the master key only performs small-volume operations, so it can live inside hardware or a managed service under tight guard. Second, rotating the master key only requires re-wrapping data keys, leaving the data itself untouched, which makes rotation frequent and cheap. Third, data keys are cleared from memory after use, so a single leaked data key affects only a single object. Checkpoints: data keys must be generated from a cryptographically secure random source; wrap and unwrap operations must leave audit logs; plaintext data keys must never be written to logs or disk.
The KMS boundary: applications hold references only
The value of a key management service (KMS) or hardware security module is that it gathers generation, storage, usage control, and auditing of master keys into one dedicated component. The correct posture on the application side: code stores only the key’s identifier (a reference); to encrypt, it sends the data key to be wrapped to the KMS, the KMS performs the operation internally and returns the result, and the plaintext master key never leaves the KMS boundary.
This boundary buys two direct benefits. Permissions can be fine-grained — which service, under what conditions, may invoke which master key for which operation — and every call is recorded, so anomalous calls can be detected. And rotation and revocation become configuration operations: master keys roll over inside the KMS without applications noticing; if an environment is suspected compromised, the corresponding key version can be disabled so new data is rerouted immediately. Checkpoints: production and test environments use different master keys; application identities get least-privilege grants, with no single service account holding every key; KMS call logs are reviewed regularly, watching for unwrap requests from unusual sources or at unusual hours.
Environment variables: an injection channel, not a vault
Putting keys in environment variables is better than hardcoding them, but their role must be stated correctly: environment variables solve the problem of “keys are not distributed with the code”, not the problem of “keys are stored safely”. Other processes on the same machine, crash dumps, debugging interfaces, and accidentally logged output (many frameworks print the full environment at startup) can all read them; child processes also inherit the parent’s environment by default, so keys quietly spread to programs that should never have touched them.
Environment variables are therefore suitable only for development and small deployments: long-term keys in production should preferably be fetched at runtime from a KMS or a dedicated secrets distribution service, and environment variables should carry at most the reference information for where to fetch keys (such as a KMS address and role name), never the key material itself. Checkpoints: framework and logging configuration explicitly excludes printing environment variables; crash dumps are redacted; orchestration manifests that are widely queryable must not contain key values.
Wrap-up: a layered checklist
Combined, the four rules form a checklist that can go straight into a code review template: is key material entirely absent from code and repositories; does bulk data go through envelope encryption, with data keys randomly generated and discarded after use; do master keys exist only inside the KMS boundary, with applications holding references and least-privilege access; and do environment variables contain only references rather than key material. Pass all four, and key storage reaches the engineering bar — the prerequisite for every cryptographic feature built on top of it to operate safely.
Tags: Key ManagementEnvelope EncryptionKMSSecure Coding