Secrets Management and Encryption: Vaults, Envelope Encryption and Key Rotation


System Design Phase 12: Security & Identity
Applied Lesson 72 of 86 16 min read Updated Nov 30, 2026

A developer debugging a failing integration test pastes a production database URL into a .env.example file and pushes it to a public repository at 14:02. Automated scanners that watch public pushes find credentials within minutes. By 14:09 someone has connected. The password is the same one the service has used for three years, because rotating it means editing 14 deployment configs and restarting everything, so nobody ever did.

Now count what has to happen. Rotate the password, which breaks every service still using the old one. Work out what the attacker read, which is hard because the database logs who connected, not which rows left. And ask whether the backups, which use the same credential chain, are exposed too.

Every step is painful because the secret was long-lived, shared, copied into many places and never designed to change. This article is about building the opposite: secrets that are short-lived, issued per workload, rotated by machines, and data encrypted with keys you can rotate and destroy on purpose.

What it is

Two related disciplines:

  • Secrets management handles credentials that grant access: database passwords, API keys, signing keys, OAuth client secrets, TLS private keys. The goals are that secrets never live in code, are delivered only to the workloads that need them, expire quickly, and can be rotated without an outage.
  • Encryption protects data so that stolen bytes are useless without a key. Encryption in transit protects data on the wire, encryption at rest protects data on disk, in backups and in object storage. The hard part is never the cipher. It is key management: where keys live, who can use them, how they rotate and how you prove it.

The best secret is the one you do not need. Workload identity, covered in mTLS and workload identity, removes most static cloud credentials entirely. What remains goes in a secret manager.

How it works

The secrets lifecycle

  1. Create secrets inside a secret manager, never on a laptop.
  2. Store them encrypted, with access policies per secret and an audit trail of every read.
  3. Deliver them at runtime to an authenticated workload, ideally as a file or via an API, not baked into images.
  4. Rotate on a schedule and on suspicion, with overlap so old and new both work during the switch.
  5. Revoke and delete when a workload is retired.

Never in git. Git history is permanent and forks copy it. If a secret was ever committed, treat it as leaked and rotate it; deleting the commit is not enough.

Environment variables are a delivery format, not a vault. They are convenient and better than hard-coding, but they leak: child processes inherit them, crash reporters and debug endpoints dump them, docker inspect and the Kubernetes pod spec show them, and on Linux /proc/<pid>/environ exposes them to anyone with the right access on the host. Prefer mounted files with tight permissions, or have the app fetch from the secret manager at start-up, and never log the environment.

Secret managers

  • HashiCorp Vault is the most widely deployed self-hosted secret manager: KV storage, dynamic secrets engines, a PKI engine and a transit (encryption as a service) engine. HashiCorp moved Vault to the Business Source License in 2023 and IBM completed its acquisition of HashiCorp in 2025.
  • OpenBao is the open source fork of Vault 1.14 under the MPL 2.0 licence, developed under the Linux Foundation’s OpenSSF. It is API compatible with most Vault clients.
  • AWS Secrets Manager stores secrets encrypted with KMS keys and has managed rotation for RDS, Aurora and other services through rotation Lambdas.
  • Google Secret Manager and Azure Key Vault cover the same ground on their clouds.

Kubernetes Secrets are not encryption. A Secret object is base64-encoded, which is an encoding, not a cipher. By default it is stored in etcd as plaintext, and anyone who can read Secrets in a namespace, or create a pod there that mounts them, can read them. Minimum hardening: enable encryption at rest for etcd with a KMS provider (the KMS v2 provider is the current design), restrict get and list on Secrets through RBAC, and keep the source of truth outside the cluster. The External Secrets Operator syncs secrets from Vault, OpenBao, AWS, GCP or Azure into Kubernetes Secrets, and the Secrets Store CSI driver mounts them directly as files. Kubernetes basics are covered later in containers and Kubernetes.

Dynamic and short-lived credentials

A static database password shared by 40 pods is the problem from the opening. Dynamic secrets invert it: when a workload starts, it authenticates to Vault or OpenBao with its workload identity, and the database secrets engine creates a brand new database user with a 1 hour lease. When the lease expires the user is dropped. Every pod has its own credential, a leak is useful for an hour, and audit logs map every database session to one pod.

The same pattern appears everywhere: AWS STS temporary credentials, GCP short-lived service account tokens, OAuth access tokens measured in minutes. The design rule is: prefer credentials that expire over credentials you must remember to rotate.

Rotation without downtime

For secrets that must stay static (a third-party API key, a webhook signing secret), rotation needs two valid versions at once:

  1. Create the new version; the provider accepts both old and new.
  2. Roll it out to every consumer and confirm through logs or metrics that none still use the old one.
  3. Revoke the old version.

Secret managers model this with version stages (AWS Secrets Manager uses AWSCURRENT and AWSPENDING, for example). Skipping step 2 is how rotation causes outages, and outages are why teams stop rotating.

Encryption in transit

TLS 1.3 on every hop, including internal ones: client to edge, edge to service, service to service (mTLS in a mesh), service to database, and replication links between databases. “It is inside the VPC” is not a reason to skip it, because the threat is often an attacker already inside. Certificates and identity for the internal hops are covered in mTLS.

Encryption at rest, in three layers

Layer Protects against Does not protect against
Disk or volume encryption (EBS, persistent disk) Stolen or improperly disposed drives Anyone who can query the running database
Database TDE or managed storage encryption Stolen data files, snapshots and backups SQL injection, over-privileged users
Application-level (field) encryption Database admins, DB compromise, leaked dumps A compromised application that holds the key

Each layer protects against attackers below it. Cloud disk and managed database encryption are effectively free and should be on everywhere. Application-level encryption costs you querying (you cannot WHERE on ciphertext unless you add deterministic encryption or blind indexes) and is reserved for the most sensitive fields: national IDs, health data, payment details, secrets you store for customers.

Envelope encryption with KMS

A KMS (AWS KMS, Google Cloud KMS, Azure Key Vault, or an HSM-backed Vault transit engine) holds key encryption keys (KEKs) that never leave it. You do not send gigabytes to KMS. Instead:

  1. Ask KMS for a fresh data encryption key (DEK). KMS returns it twice: in plaintext and encrypted (wrapped) under the KEK.
  2. Encrypt the data locally with the plaintext DEK using AES-256-GCM.
  3. Store the wrapped DEK next to the ciphertext. Discard the plaintext DEK from memory.
  4. To decrypt, send the wrapped DEK to KMS, which checks the caller’s permission, unwraps it and returns the plaintext DEK.
sequenceDiagram
participant App as Service
participant KMS as KMS (holds KEK)
participant S as Object store
App->>KMS: GenerateDataKey(KEK id)
KMS-->>App: DEK plaintext + DEK wrapped by KEK
App->>App: AES-256-GCM encrypt file with DEK
App->>App: Wipe DEK plaintext from memory
App->>S: Put ciphertext + wrapped DEK + KEK id
Note over App,S: Later, to read
App->>S: Get ciphertext + wrapped DEK
App->>KMS: Decrypt(wrapped DEK), IAM checked, logged
KMS-->>App: DEK plaintext
App->>App: Decrypt file locally

Envelope encryption gives you fast local crypto on large data, a KMS call per object rather than per byte, central access control and audit on every unwrap, and cheap key rotation. Most cloud services, including S3 server-side encryption with KMS keys and Kubernetes KMS v2, are built this way.

flowchart TB
R["Root key<br/>in HSM, never exported"] --> K1["KEK: tenant-acme<br/>in KMS"]
R --> K2["KEK: tenant-globex<br/>in KMS"]
K1 --> D1["DEK per object<br/>wrapped by tenant-acme KEK"]
K1 --> D2["DEK per object"]
K2 --> D3["DEK per object"]
D1 --> C1["Ciphertext"]
D2 --> C2["Ciphertext"]
D3 --> C3["Ciphertext"]
style R fill:#FCEBEB,stroke:#A32D2D,color:#791F1F
style K1 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style K2 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style D1 fill:#FAEEDA,stroke:#854F0B,color:#633806
style D2 fill:#FAEEDA,stroke:#854F0B,color:#633806
style D3 fill:#FAEEDA,stroke:#854F0B,color:#633806
style C1 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style C2 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style C3 fill:#E1F5EE,stroke:#0F6E56,color:#085041

Crypto-shredding for deletion

Deleting data from every replica, cache, log and backup is close to impossible. Encrypting each subject’s or tenant’s data under its own key and destroying the key makes the remaining ciphertext unreadable everywhere at once. This is how teams meet erasure requests in systems with immutable logs, such as event sourcing, and in long-retention backups covered in disaster recovery. Two caveats: it only works if plaintext copies never escaped (search indexes, analytics exports, caches), and whether it satisfies a specific legal erasure obligation is a question for your counsel, not an engineering assumption.

Hashing vs encryption vs tokenization

  • Hashing is one-way. Use it for passwords with a slow, salted algorithm (Argon2id, scrypt or bcrypt), never plain SHA-256. Use keyed hashes (HMAC) for integrity and for blind indexes that let you look up encrypted fields.
  • Encryption is reversible with a key. Use authenticated encryption (AES-GCM, ChaCha20-Poly1305) so tampering is detected.
  • Tokenization replaces a value with a random token and keeps the mapping in a separate, tightly controlled vault. Card networks and payment processors use it so that most systems handle tokens and fall outside the strictest compliance scope. Unlike encryption, a token has no mathematical relationship to the original.

Where it breaks

Secret sprawl. The same credential ends up in CI variables, a wiki, three Helm values files and a Slack message. Secret scanning catches the obvious copies: GitHub push protection blocks known token formats at push time, and tools such as Gitleaks and TruffleHog scan history and CI logs. Scanning is a net, not a strategy; short-lived credentials are the strategy.

The secret zero problem. To fetch secrets from Vault, the app needs a credential for Vault. If that is a static token in an environment variable, you have moved the problem. Solve it with platform identity: Kubernetes service account tokens, cloud instance identity, or SPIFFE SVIDs, which the platform injects and rotates.

KMS as a single point of failure. If KMS is down or throttling, nothing decrypts. Cache DEKs with bounded lifetimes, handle throttling with backoff (see timeouts, retries and backoff), and for multi-region systems use per-region keys or multi-region keys so a regional outage does not block reads elsewhere.

Encryption that protects nothing. Disk encryption does not stop SQL injection. If the application’s credentials can call KMS Decrypt on everything, field encryption does not stop a compromised application. Write down the attacker you are defending against for each layer.

Losing keys is losing data. Deleting or disabling the wrong KEK is an instant, unrecoverable outage. Use deletion waiting periods, require two people to schedule key deletion, and alarm on any use of a key that is pending deletion.

Supply chain. Attackers increasingly steal secrets by compromising what you build with: a poisoned dependency, a tampered CI runner, a malicious GitHub Action. Basics that are now table stakes:

  • SBOM (software bill of materials, in SPDX or CycloneDX format) for every artifact so you can answer “are we running the vulnerable version?” in minutes.
  • SLSA (Supply-chain Levels for Software Artifacts), an OpenSSF framework whose build track levels describe how trustworthy your build provenance is, from documented builds up to hardened, isolated builders.
  • Sigstore for signing: cosign signs container images and artifacts with short-lived certificates from the Fulcio CA tied to a CI workload identity, and records them in the Rekor transparency log, so there is no long-lived signing key to leak. npm provenance and many container registries build on it.
  • Pin dependencies and CI actions by digest, and give CI jobs short-lived cloud credentials through OIDC federation rather than stored keys.

Post-quantum key exchange

An attacker who records TLS traffic today could decrypt it once a large quantum computer exists (“harvest now, decrypt later”). Key exchange is the urgent part, because signatures only matter at the moment of the handshake. NIST standardised ML-KEM (FIPS 203) in August 2024, and TLS now uses a hybrid group, X25519MLKEM768, which combines classical X25519 with ML-KEM-768 so the connection is safe if either one holds.

As of late 2026 it is on by default in Chrome (since version 131), Firefox (since 132 on desktop) and Apple’s OS 26 releases, in Go’s standard library since Go 1.24, and in OpenSSL since 3.5. Cloudflare reported that a majority of human traffic to its network used post-quantum key exchange by late October 2025. Origins lag far behind, so the work for most teams is upgrading the TLS libraries on their own servers and internal hops. Post-quantum certificates and signatures are much less mature and not yet a default anywhere on the public web.

Real-world systems

  • HashiCorp Vault and OpenBao: KV, dynamic database and cloud credentials, PKI, transit encryption.
  • AWS KMS, Google Cloud KMS, Azure Key Vault: managed KEKs, envelope encryption, automatic key rotation, deletion waiting periods.
  • AWS Secrets Manager, Google Secret Manager: managed secret storage with versioning and rotation hooks.
  • Kubernetes: Secrets plus etcd encryption with KMS v2, External Secrets Operator, Secrets Store CSI driver.
  • Sigstore (cosign, Fulcio, Rekor), SLSA, SPDX and CycloneDX SBOMs for the supply chain.
  • Cloudflare, Chrome, Firefox, Go, OpenSSL for hybrid post-quantum TLS key exchange.

How to apply it

Defaults for a new system:

  • Workload identity to cloud APIs, no static access keys anywhere.
  • One secret manager as the source of truth; Kubernetes Secrets only as a synced, encrypted cache.
  • Dynamic database credentials where the engine supports it; otherwise automated rotation with dual versions.
  • TLS 1.3 everywhere, mTLS between services, hybrid post-quantum key exchange enabled where your libraries support it.
  • Disk and managed database encryption on everywhere, envelope encryption with per-tenant KEKs for sensitive fields and files.
  • Crypto-shredding designed in from day one if you have erasure obligations.
  • Secret scanning in pre-commit, at push and in CI; SBOMs and signed artifacts from CI.

Choosing a protection:

Data Protection
User passwords Argon2id or bcrypt hash, never encryption
Card numbers Tokenization through a payment provider
Health records, national IDs Application-level envelope encryption, per-tenant KEK
General business data Managed database and disk encryption plus TLS
API keys you issue to customers Store only a hash, show the key once

Interview questions

Q1: Why use envelope encryption instead of sending data to KMS directly?

Model answer: KMS APIs accept only small payloads (AWS KMS Encrypt takes at most 4 KB), are rate limited, and add a network round trip per call. With envelope encryption you encrypt bulk data locally with a DEK using AES-GCM and only send the small DEK to KMS for wrapping and unwrapping. The KEK never leaves KMS, so access control and audit still happen centrally on every unwrap. Rotating the KEK means re-wrapping small DEKs, or relying on the KMS’s own key versioning, instead of re-encrypting all the data.

Q2: A database password was committed to a public repository an hour ago. What do you do?

Model answer: Rotate immediately, assuming it is already used: create a new credential, roll it to consumers, then revoke the old one, accepting a brief disruption if needed because the exposure is worse. Check database and network logs for connections from unknown sources since the commit and scope what they could reach. Remove the secret from history for hygiene, but do not treat that as remediation. Then fix the cause: move the app to dynamic or managed-rotation credentials from a secret manager, add push protection and pre-commit scanning, and add the incident to the postmortem.

Q3: How do you delete one tenant’s data from immutable backups?

Model answer: Design for crypto-shredding: encrypt each tenant’s data with DEKs wrapped by a tenant-specific KEK. When the tenant is deleted, delete the live data normally and schedule deletion of the KEK. Backups still contain ciphertext, but without the KEK the wrapped DEKs cannot be unwrapped, so the data is unreadable. It works only if no plaintext copies exist outside the encrypted stores, such as search indexes, analytics exports or logs, so those need the same treatment or separate deletion.

✅ Key takeaways

  • The best secret is no secret: use workload identity and dynamic, short-lived credentials before reaching for a vault.
  • Kubernetes Secrets are base64, not encrypted; enable etcd encryption with KMS and sync from a real secret manager with the External Secrets Operator.
  • Rotation needs two valid versions and proof that consumers switched, or it causes the outages that stop teams rotating.
  • Envelope encryption keeps the KEK inside KMS and encrypts data locally with per-object DEKs, making rotation a cheap re-wrap and enabling crypto-shredding.
  • Hash passwords with a slow algorithm, encrypt with authenticated ciphers, and tokenize payment data.
  • Hybrid ML-KEM key exchange (X25519MLKEM768) is default in major browsers and on Cloudflare; upgrade your own servers’ TLS libraries to match.

🧠 Check your understanding

0 / 4
  1. 1A team stores database passwords in Kubernetes Secrets and says they are encrypted because the values look scrambled. What is true by default?

  2. 2With envelope encryption, what happens when you enable automatic rotation on an AWS KMS key?

  3. 3Which is the right way to store user login passwords?

  4. 4Why do major browsers use the hybrid X25519MLKEM768 group rather than ML-KEM alone?

Where to go next

Finished this lesson?

Mark it complete to track your progress across the roadmap.