Sub topic 7
Envelope encryption with data keys
This chapter assumes you can run the AWS CLI and read Python. It also assumes you know what plaintext and ciphertext are, and you have created the alias/tutorial-key key from the earlier chapters. You should also know that the direct Encrypt call is limited to small payloads.
Why direct Encrypt is not enough
The KMS Encrypt operation accepts at most 4,096 bytes of plaintext. Every call also travels over the network to KMS, and each call counts against a request quota. That is fine for a short secret. It does not work for a database backup, a video, or a million records.
Envelope encryption solves both problems. You do not send your data to KMS. You ask KMS for a data key, encrypt the data locally with that key, and keep an encrypted copy of the data key next to the ciphertext.
A data key is a symmetric key that your application uses to encrypt data outside KMS. The KMS key that protects it is called the wrapping key, because it "wraps" (encrypts) the data key. The KMS key never leaves KMS. The data key exists in plaintext only briefly, in your application's memory.
How the pieces fit together
The flow has these properties:
- KMS sees only the small data key, never your data.
- The storage holds the ciphertext and the encrypted data key, and neither is useful alone.
- To read the data, a caller needs
kms:Decryptpermission on the KMS key. Controlling that permission controls access to the data. - Each object can have its own data key, so one leaked data key exposes one object.
Generating a data key
GenerateDataKey returns two copies of the same key:
| Field | Content | What you do with it |
|---|---|---|
| `Plaintext` | The raw data key | Use it to encrypt locally, then discard it |
| `CiphertextBlob` | The same key, encrypted under your KMS key | Store it next to the encrypted data |
| `KeyId` | The ARN of the KMS key that was used | Optional to store; useful for logging |
You choose the key size with KeySpec (AES_256 or AES_128) or with NumberOfBytes. For most work, use AES_256.
Try it from the CLI to see the response shape:
aws kms generate-data-key \
--key-id alias/tutorial-key \
--key-spec AES_256 \
--encryption-context purpose=demo \
--query '{Encrypted:CiphertextBlob,Arn:KeyId}'The CLI base64-encodes binary fields. The SDK for Python, boto3, returns raw bytes, which is what the next example uses.
The full example in Python
This code uses the cryptography package (pip install boto3 cryptography). It encrypts with AES-GCM, an authenticated cipher. Authenticated means decryption fails if anyone has changed the ciphertext.
import os
import boto3
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
kms = boto3.client("kms")
CONTEXT = {"purpose": "demo"}
def encrypt(plaintext: bytes) -> dict:
resp = kms.generate_data_key(
KeyId="alias/tutorial-key",
KeySpec="AES_256",
EncryptionContext=CONTEXT,
)
nonce = os.urandom(12)
ciphertext = AESGCM(resp["Plaintext"]).encrypt(nonce, plaintext, None)
return {
"encrypted_key": resp["CiphertextBlob"],
"nonce": nonce,
"ciphertext": ciphertext,
}
def decrypt(blob: dict) -> bytes:
resp = kms.decrypt(
CiphertextBlob=blob["encrypted_key"],
EncryptionContext=CONTEXT,
)
return AESGCM(resp["Plaintext"]).decrypt(blob["nonce"], blob["ciphertext"], None)
if __name__ == "__main__":
blob = encrypt(b"a payload far larger than 4 KB could go here")
print(decrypt(blob))Walk through what each part does:
generate_data_keyreturns the plaintext and encrypted copies of a fresh 256-bit key.os.urandom(12)creates a 12-byte nonce, a value that must be unique for each encryption with the same key. AES-GCM breaks badly if a nonce repeats under one key. Because every call here gets a fresh data key, repeats are not a risk, but you still store the nonce, since decryption needs it.AESGCM(...).encryptproduces the ciphertext. The last argument,None, is optional associated data, which is extra data that is authenticated but not encrypted.encryptreturns the encrypted key, nonce, and ciphertext. You store all three together, for example in one file or one database row.decryptsends only the encrypted key to KMS. The call needs noKeyId, because for symmetric keys the ciphertext records which KMS key made it. KMS returns the plaintext key, and the local cipher does the rest.
The EncryptionContext must match on both calls. If it differs, decrypt raises an InvalidCiphertextException. The next chapter covers encryption context in detail. Here it is enough to know that it is part of what KMS checks before it releases the data key.
Choosing a variant of GenerateDataKey
KMS offers several related operations. Pick by whether the caller needs the plaintext key right now.
| Operation | Returns plaintext key? | Typical use |
|---|---|---|
| `GenerateDataKey` | Yes, plus encrypted copy | Encrypt data now |
| `GenerateDataKeyWithoutPlaintext` | No, encrypted copy only | Create a key now, use it later, for example a worker that will decrypt it when needed |
| `GenerateRandom` | Random bytes only | Random bytes with no key attached |
GenerateDataKeyWithoutPlaintext is useful when one component provisions keys and a different component, with its own permissions, uses them. The provisioner never holds a usable key.
Handling the plaintext key safely
The plaintext data key is the weak point of the design. Keep these rules in mind:
- Do not write it to disk, logs, or error messages.
- Do not cache it longer than needed. If you must reuse a key for performance, limit it by age and by number of messages.
- Drop references to it as soon as you finish. In Python you cannot reliably wipe memory, so keep the key's lifetime short. In languages with mutable buffers, overwrite the key's bytes.
- Never store the plaintext key beside the ciphertext. Only the encrypted key goes into storage.
Edge cases and common errors
- Ciphertext with a missing key blob. If you lose the encrypted data key, the data is unrecoverable, even though the KMS key still exists. Store them atomically, in the same object or the same transaction.
InvalidCiphertextExceptionon decrypt. The usual causes are a mismatched encryption context, a truncated or re-encoded blob (for example base64 applied twice), or a blob created in another Region.AccessDeniedException. The caller lackskms:GenerateDataKeyfor encrypting orkms:Decryptfor reading. These are separate permissions. A role that only reads data needs onlykms:Decrypt.InvalidTagfrom the local cipher. KMS succeeded, but the ciphertext, nonce, or associated data was altered or paired with the wrong key.- Large data in memory.
AESGCM.encryptworks on a whole buffer. For files too big for memory, split the data into chunks, or use a streaming library such as the AWS Encryption SDK, which handles envelope encryption, chunking, and message formats for you. - Key deleted or disabled. If the KMS key is disabled or scheduled for deletion,
Decryptfails, and so does every stored encrypted data key that depends on it. - Rotation. Automatic rotation of the KMS key does not break old data. KMS keeps earlier key material and picks the right version from the ciphertext. You do not need to re-encrypt stored data keys.
Envelope encryption in AWS services
AWS services use this same pattern when you choose a KMS key for them. S3, EBS, and RDS each request data keys from KMS and keep the encrypted data key with the stored data. That is why granting a service access to your KMS key, covered in a later chapter, is what makes encrypted storage work. The pattern is the same as the code above, run by the service.
Exercise
Your application encrypts a 2 GB file with envelope encryption. Which value goes into storage next to the ciphertext, which value must never be stored, and which KMS permission does a read-only job need?
Show answer
Store the encrypted data key (CiphertextBlob) and the nonce next to the ciphertext. Never store the plaintext data key (Plaintext). A read-only job needs kms:Decrypt on the KMS key. It does not need kms:GenerateDataKey, because it only recovers existing data keys.
Exercise
A decrypt call fails with InvalidCiphertextException, although the KMS key is enabled and the role has kms:Decrypt. Name two likely causes in the envelope example.
Show answer
The encryption context passed to decrypt differs from the one used in generate_data_key, or the encrypted key blob was corrupted or re-encoded (for example, base64 decoded twice or truncated). A blob from a different Region also fails.