Why keys matter
Ciphers like AES are public: anyone can read how they work. Only the key is secret, so whoever holds the key can read everything. Key management means keeping keys safe for their whole life, from creation to destruction.
A common mistake is keeping a key where code or data lives: typed into source code, or saved beside the files. One leak then exposes both. The fix: keep keys in a key management service (KMS), ideally backed by a hardware security module (HSM).
One file, start to finish
Keys must come from a secure random generator, never from a password or a pattern. Line 1 makes the key-encryption key (KEK); line 2 makes a data-encryption key (DEK). Each is 256 bits: 32 random bytes.
Line 3 picks a fresh 12-byte nonce, a number used once. Line 4 encrypts the file with the DEK using AES-GCM. The 9-byte file becomes 25 bytes: the scrambled data plus a 16-byte tag that detects any change.
Line 5 encrypts the DEK itself with the KEK. This is called wrapping, and the pattern is envelope encryption. The 32-byte DEK becomes 40 bytes. In a real system the KMS wraps it inside, so the KEK never leaves.
Line 6 drops the plain DEK. The ciphertext, nonce and wrapped DEK are stored together. Anyone who copies the disk gets nothing readable: to unwrap the DEK they would also need the KMS.
To read the file, the app sends the wrapped DEK to the KMS (line 7). The KMS checks the app is allowed, logs the request, and returns the DEK. Line 8 decrypts and prints b'pay: 4200'.
Rotate and destroy
Each key has a cryptoperiod: a set time it may be used. When it ends, line 9 makes KEK v2 and line 10 re-wraps the DEK with it. Only the 40-byte wrapped key changes; the file is not re-encrypted.
Once nothing needs KEK v1, the KMS destroys it and every copy. That cannot be undone: data wrapped only by it is unreadable for good. So re-wrap first, then destroy. NIST calls doing it on purpose cryptographic erase.
Every key follows the same path: create, store, use, rotate, destroy. Write down who may use each key and for what, log every use, and plan for a leak: stop using the key, make a new one, re-wrap, check the logs.
What happens
;; step 1/10 · secret
cipher public (AES is a published standard)
key the only secret
key management create, store, use, rotate, destroy,
safely, for every key
In the code, kek is a plain Python value so the example runs on its own. In a real system the KEK never leaves the KMS or HSM: the app sends the DEK to be wrapped or unwrapped, and the service does it inside. del removes the name dek, but Python cannot promise the bytes are wiped from memory at once. Key management services and HSMs handle wiping (zeroization) for you; that is one more reason to let them hold keys.