Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 20 min · revision 2

Key Lifecycle and Envelope Encryption

Follow a key from generation to destruction. Learn why applications ask a KMS or vault for keys instead of holding them, how envelope encryption works, and what rotation, rewrapping, retiring a version and crypto-shredding really do, using a small local KMS model you can run.

Contentsand lesson path

What you will learn

  • Design key generation, storage, rotation and destruction for an application using a KMS or vault instead of hard-coded keys.

01. Why it matters

AES-256-GCM is, as far as anyone knows, unbreakable when used correctly. So attackers rarely attack the cipher. They look for the key. They find it in a configuration file committed to a repository, in an environment variable printed by a crash report, in a container image layer, or in the same backup as the data it protects. At that point the strength of the cipher no longer matters: the attacker decrypts with your key, exactly as your application does.

Key management is the discipline of deciding where keys are created, where they live, who and what may use them, how they are replaced, and how they are destroyed. It is less exciting than algorithms and much more often the reason for a breach. The good news is that you rarely need to build it: cloud key management services (KMS) such as AWS KMS, Google Cloud KMS and Azure Key Vault, and self-hosted vaults such as HashiCorp Vault or OpenBao, do the hard parts. Your job is to design how your application uses them.

02. The life of a key

NIST SP 800-57 Part 1 describes keys as moving through states over their life. A practical version for application developers has five stages.

  1. Generation. Keys come from a cryptographically secure random generator, ideally inside the KMS or a hardware security module (HSM), so the key material never exists anywhere else. A key derived from a password, a timestamp or the random module is not a key.
  2. Storage. The master keys stay inside the KMS. Your application holds only a credential to ask the KMS for operations, such as an IAM role or a workload identity, and never the key itself. This is the difference between a KMS and a secrets manager: a secrets manager hands a secret back to you, a KMS performs the operation and keeps the key.
  3. Use. Each key has one purpose (encrypting data keys for one service, say) and an access policy that names who may encrypt and who may decrypt. Every request is logged, which turns "who read the payroll data?" into a question you can answer.
  4. Rotation. New key material is introduced on a schedule or on demand. Old versions are kept so that existing data stays readable; new encryptions use the newest version.
  5. Retirement and destruction. A version or key is first disabled, so that nothing can use it, then destroyed after a waiting period. AWS KMS, for example, requires a waiting period of 7 to 30 days before deleting a key, because deletion makes everything encrypted under it permanently unreadable.

Notice how much of this is about people and permissions, not mathematics. Separating the right to manage a key from the right to use it, and the right to encrypt from the right to decrypt, is what stops one stolen credential from exposing everything.

03. Envelope encryption

A KMS is a remote service with request limits and network latency, so you cannot send it every database row. Envelope encryption solves this with two layers of keys. A data key (often called a DEK, data encryption key) encrypts the data locally, and a key encryption key (KEK) inside the KMS encrypts, or wraps, the data key. You store the wrapped data key next to the ciphertext and throw the plaintext data key away. To read the data, you send the small wrapped key to the KMS, get the data key back, and decrypt locally.

Most KMS APIs also accept an encryption context: a few non-secret key-value pairs, such as a tenant id, that must be supplied again at decryption time. The KMS binds them to the wrapped key as associated data, so a wrapped key copied into another tenant's record will not unwrap, and every audit log entry shows the context.

You cannot run AWS KMS on a laptop, so the code below is a small local model of one, about 85 lines, built on AES-GCM. It keeps key versions, an encryption context, a minimum decryption version, destruction and an audit log, and its method names mirror real APIs: generate_data_key is like AWS GenerateDataKey, and rewrap is like AWS ReEncrypt or the Vault Transit rewrap endpoint. It is for learning only; a real KMS keeps its keys in hardened hardware. Use the same environment as the earlier lessons in this skill (Python 3.12, cryptography==50.0.2).

Python · local_kms.py
"""A tiny local stand-in for a cloud KMS, for learning only.

Real services (AWS KMS, Google Cloud KMS, Azure Key Vault, Vault Transit) keep key
material inside hardware or a hardened service; you only ever send them requests.
"""
import base64
import json
import os

from cryptography.hazmat.primitives.ciphers.aead import AESGCM


class KeyUnavailable(Exception):
    pass


class LocalKMS:
    def __init__(self) -> None:
        self._keys: dict[str, dict] = {}
        self.audit: list[str] = []

    def create_key(self, key_id: str) -> None:
        self._keys[key_id] = {"versions": {1: AESGCM.generate_key(bit_length=256)},
                              "primary": 1, "min_decrypt": 1, "state": "enabled"}

    def _aad(self, key_id: str, version: int, context: dict) -> bytes:
        return json.dumps([key_id, version, context], sort_keys=True).encode()

    def _key(self, key_id: str) -> dict:
        key = self._keys[key_id]
        if key["state"] != "enabled":
            raise KeyUnavailable(f"{key_id} is {key['state']}")
        return key

    def generate_data_key(self, key_id: str, context: dict) -> tuple[bytes, str]:
        """Return (plaintext data key, wrapped data key). Store only the second."""
        key = self._key(key_id)
        version = key["primary"]
        dek, nonce = AESGCM.generate_key(bit_length=256), os.urandom(12)
        wrapped = AESGCM(key["versions"][version]).encrypt(
            nonce, dek, self._aad(key_id, version, context))
        self.audit.append(f"GenerateDataKey {key_id} v{version} {context}")
        return dek, f"{key_id}:v{version}:" + base64.b64encode(nonce + wrapped).decode()

    def _unwrap(self, wrapped: str, context: dict) -> tuple[str, int, bytes]:
        key_id, v, blob = wrapped.split(":", 2)
        version, raw = int(v[1:]), base64.b64decode(blob)
        key = self._key(key_id)
        if version < key["min_decrypt"]:
            raise KeyUnavailable(f"{key_id} v{version} is below min_decrypt")
        dek = AESGCM(key["versions"][version]).decrypt(
            raw[:12], raw[12:], self._aad(key_id, version, context))
        return key_id, version, dek

    def decrypt(self, wrapped: str, context: dict) -> bytes:
        ref = ":".join(wrapped.split(":")[:2])
        self.audit.append(f"Decrypt {ref} {context}")  # failed attempts are logged too
        return self._unwrap(wrapped, context)[2]

    def rotate(self, key_id: str) -> int:
        key = self._key(key_id)
        key["primary"] = max(key["versions"]) + 1
        key["versions"][key["primary"]] = AESGCM.generate_key(bit_length=256)
        self.audit.append(f"RotateKey {key_id} -> v{key['primary']}")
        return key["primary"]

    def rewrap(self, wrapped: str, context: dict) -> str:
        """Re-encrypt a data key under the primary version; the caller never sees it."""
        key_id, old_version, dek = self._unwrap(wrapped, context)
        key = self._key(key_id)
        version, nonce = key["primary"], os.urandom(12)
        self.audit.append(f"ReEncrypt {key_id} v{old_version} -> v{version}")
        new = AESGCM(key["versions"][version]).encrypt(
            nonce, dek, self._aad(key_id, version, context))
        return f"{key_id}:v{version}:" + base64.b64encode(nonce + new).decode()

    def set_min_decrypt(self, key_id: str, version: int) -> None:
        self._key(key_id)["min_decrypt"] = version

    def destroy(self, key_id: str) -> None:
        """After the waiting period: the key material is gone for good."""
        self._keys[key_id] = {"versions": {}, "state": "destroyed"}
        self.audit.append(f"DeleteKey {key_id}")
Python · envelope.py
"""Envelope encryption: a fresh data key per record, wrapped by the KMS key."""
import os

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

from local_kms import LocalKMS


def encrypt_record(kms: LocalKMS, key_id: str, tenant: str, text: str) -> dict:
    context = {"tenant": tenant}
    dek, wrapped = kms.generate_data_key(key_id, context)
    nonce = os.urandom(12)
    ct = AESGCM(dek).encrypt(nonce, text.encode(), tenant.encode())
    del dek  # use the plaintext key once, then drop it; never store or log it
    return {"tenant": tenant, "wrapped_key": wrapped, "nonce": nonce, "ct": ct}


def decrypt_record(kms: LocalKMS, record: dict, tenant: str) -> str:
    dek = kms.decrypt(record["wrapped_key"], {"tenant": tenant})
    return AESGCM(dek).decrypt(record["nonce"], record["ct"], tenant.encode()).decode()

The del dek line states intent more than it achieves: Python cannot reliably wipe memory, so the key bytes may linger until the memory is reused. That limitation is one reason why the long-lived, high-value keys stay inside the KMS and only short-lived data keys ever reach application memory.

04. Rotation, rewrapping, retirement and destruction

The script below walks two tenants' keys through the whole lifecycle. Read each numbered line of output against the code before you read the explanation.

Python · lifecycle.py
"""Walk one key through its life: use, rotate, rewrap, retire, destroy."""
from cryptography.exceptions import InvalidTag

from envelope import decrypt_record, encrypt_record
from local_kms import KeyUnavailable, LocalKMS

kms = LocalKMS()
kms.create_key("acme")
kms.create_key("globex")

old = encrypt_record(kms, "acme", "acme", "invoice 1001: 250 GBP")
archive = encrypt_record(kms, "acme", "acme", "invoice 0999: 40 GBP")  # also v1
print("1 stored fields:", sorted(old), "| key ref:", old["wrapped_key"][:8])
print("1 decrypt:", decrypt_record(kms, old, "acme"))

try:
    decrypt_record(kms, old, "globex")  # right blob, wrong encryption context
except InvalidTag:
    print("2 wrong context: refused by the KMS")

kms.rotate("acme")
new = encrypt_record(kms, "acme", "acme", "invoice 1002: 90 GBP")
print("3 after rotation, new record uses:", new["wrapped_key"][:8])
print("3 old record still readable:", decrypt_record(kms, old, "acme"))

ct_before = old["ct"]
old["wrapped_key"] = kms.rewrap(old["wrapped_key"], {"tenant": "acme"})
print("4 rewrapped old key to:", old["wrapped_key"][:8],
      "| data ciphertext unchanged:", old["ct"] == ct_before)

kms.set_min_decrypt("acme", 2)  # retire v1, but nobody rewrapped the archive record
try:
    decrypt_record(kms, archive, "acme")
except KeyUnavailable as err:
    print("5 retired version:", err)

lost = encrypt_record(kms, "globex", "globex", "contract terms")
kms.destroy("globex")  # e.g. the tenant left and asked for erasure
try:
    decrypt_record(kms, lost, "globex")
except KeyUnavailable as err:
    print("6 after destruction:", err)

print("audit log:")
for line in kms.audit:
    print(" ", line)
Terminal
python lifecycle.py
Expected output
1 stored fields: ['ct', 'nonce', 'tenant', 'wrapped_key'] | key ref: acme:v1:
1 decrypt: invoice 1001: 250 GBP
2 wrong context: refused by the KMS
3 after rotation, new record uses: acme:v2:
3 old record still readable: invoice 1001: 250 GBP
4 rewrapped old key to: acme:v2: | data ciphertext unchanged: True
5 retired version: acme v1 is below min_decrypt
6 after destruction: globex is destroyed
audit log:
  GenerateDataKey acme v1 {'tenant': 'acme'}
  GenerateDataKey acme v1 {'tenant': 'acme'}
  Decrypt acme:v1 {'tenant': 'acme'}
  Decrypt acme:v1 {'tenant': 'globex'}
  RotateKey acme -> v2
  GenerateDataKey acme v2 {'tenant': 'acme'}
  Decrypt acme:v1 {'tenant': 'acme'}
  ReEncrypt acme v1 -> v2
  Decrypt acme:v1 {'tenant': 'acme'}
  GenerateDataKey globex v1 {'tenant': 'globex'}
  DeleteKey globex
  Decrypt globex:v1 {'tenant': 'globex'}

Line 1 shows what the database holds: the tenant, the wrapped key, the nonce and the ciphertext. There is no plaintext key anywhere. Line 2 shows the encryption context at work: the right wrapped key with the wrong tenant is refused, and the refusal appears in the audit log.

Lines 3 and 4 are the core of rotation. Rotating the KMS key added version 2 and made it the default for new data keys; version 1 still exists, so old records stay readable without any batch job. AWS documents the same behaviour, and adds an important warning: rotating the KMS key does not change any data key and does not re-encrypt any data. Rewrapping is the next step when you want old records to depend only on the new version: the KMS unwraps the data key and wraps it again under the newest version, without ever returning it to the caller. The data ciphertext is untouched, which is why rewrapping millions of records is cheap.

Line 5 shows why you rewrap before retiring a version. Setting the minimum decryption version to 2 is what you do once you no longer trust version 1, but the archive record was never rewrapped and is now unreadable. Real migrations therefore run as: rotate, rewrap everything, check that nothing still refers to the old version, and only then retire it.

Line 6 is crypto-shredding: destroying a key to make every copy of the data encrypted under it unreadable, including copies in backups that you cannot edit. This only works if each tenant, or each class of data that may need erasing, has its own key, which is a design decision you make on day one. Remember also what rotation does not fix. If a plaintext data key leaks, for example in a memory dump, rotating or rewrapping the KEK does nothing for that data; the records it protects must be re-encrypted under a new data key.

05. Getting keys out of code

The most common key-management bug is a key in source code or configuration. Removing it in a new commit does not help, because version control keeps the history, and every clone, fork and CI cache has a copy. Treat any key that reached a repository as compromised: create a new one in the KMS, re-encrypt what the old key protected, revoke the old key, and add secret scanning, such as a pre-commit hook and the scanning built into your code host, to catch the next one.

In the target design, the application has no long-term secret at all. It runs with a workload identity (for example an IAM role on AWS, a service account on Kubernetes or Google Cloud, or Vault's Kubernetes auth method), and the KMS policy allows that identity to call GenerateDataKey and Decrypt with its own encryption context and nothing else. Administrators who can rotate or schedule deletion of the key are a different group, and none of them can decrypt data.

06. Check your understanding

Practice check · 3 questions

Keys in practice

Think about which key each action actually touches.

Q1. A bug makes the application call `decrypt_record(kms, record, "globex")` on a record that belongs to `acme`. What does `local_kms.py` do?
Q2. A crash dump from one application server contained a plaintext data key. Which action actually protects the records encrypted with that data key?
Q3. A developer finds an AES key in `config.py` on the main branch of a private repository. What is the right response?
Practice only: not graded, not saved, not evidence.

07. Apply it

Give your file-encryption CLI a per-file data key wrapped by a master key, as the skill project requires. Start with local_kms.py behind an interface of your own (wrap, unwrap, rotate), so that you could later swap in a real KMS client. Add a rotate-master command that rewraps every file's data key without touching file contents, and tests showing that a file encrypted before rotation still opens, that a wrong encryption context fails, and that a destroyed key makes its files unreadable.

08. Review prompt

Without looking back: name the five stages of a key's life and one control at each stage. Explain what is stored next to an envelope-encrypted record, what rotating the KMS key does and does not change, and why you rewrap before retiring an old key version.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check