KMS and Envelope Encryption
Overview
AWS Key Management Service (KMS) creates and controls encryption keys. Keys never leave KMS in plaintext; instead you ask KMS to encrypt, decrypt or generate data keys, and every request is authorised by IAM and the key policy and logged in CloudTrail.
KMS limits direct encryption to 4 KB, so for larger data we use envelope encryption. It is like a safe-deposit system: a master key stays locked in the bank vault (KMS) while you receive a one-time key (the data key) to lock your own box. You store the box with an encrypted copy of the one-time key attached; later the bank unlocks only the one-time key, and you open the box yourself.
Services such as S3, EBS, RDS, DynamoDB and Lambda use KMS behind the scenes, but developers must understand the API calls, key policies, grants and quotas that cause real-world errors.
Key Concepts
- Key types: AWS owned, AWS managed (
aws/s3, free, auto-rotated yearly, limited policy control) and customer managed keys (full control, optional rotation,$1/monthplus requests). - Symmetric keys (AES-256-GCM) never leave KMS; asymmetric keys (RSA, ECC) support sign/verify or encrypt/decrypt with a public key; HMAC keys generate MACs.
- Envelope encryption:
GenerateDataKeyreturns a plaintext data key and an encrypted copy; encrypt locally, discard plaintext, store ciphertext + encrypted key. - Key policies are the primary access control (required); IAM policies work only if the key policy permits (
Principal: rootdelegating to IAM). - Grants give temporary, delegated permissions to a principal (used by AWS services like EBS).
- Encryption context is additional authenticated data (non-secret key-value pairs) bound to ciphertext and logged; decryption must supply the same context.
- Automatic rotation (customer managed symmetric keys, default every 365 days, configurable 90-2,560 days) keeps the key ID and ARN and retains old backing material.
- Keys are Regional; multi-Region keys share key material across Regions. Deleting a key has a 7-30 day waiting period and can be cancelled.
Detailed Notes
Direct encrypt vs envelope
| Approach | Data size | Network | Use |
|---|---|---|---|
Encrypt / Decrypt | Up to 4 KB | Every operation calls KMS | Small secrets, data keys |
Envelope (GenerateDataKey) | Any size | One KMS call per object | Files, large payloads |
Envelope encryption flow in Python
import boto3, os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
kms = boto3.client("kms")
KEY_ID = "alias/app-data"
def encrypt(plaintext: bytes, ctx: dict):
dk = kms.generate_data_key(KeyId=KEY_ID, KeySpec="AES_256", EncryptionContext=ctx)
nonce = os.urandom(12)
ciphertext = AESGCM(dk["Plaintext"]).encrypt(nonce, plaintext, None)
return {"edk": dk["CiphertextBlob"], "nonce": nonce, "data": ciphertext} # plaintext key discarded
def decrypt(blob: dict, ctx: dict) -> bytes:
key = kms.decrypt(CiphertextBlob=blob["edk"], EncryptionContext=ctx)["Plaintext"]
return AESGCM(key).decrypt(blob["nonce"], blob["data"], None)
In practice use the AWS Encryption SDK, which implements envelope encryption, caching and a standard message format. The AWS Database Encryption SDK handles client-side encryption of DynamoDB attributes.
Key policy
{
"Version": "2012-10-17",
"Statement": [
{ "Sid": "AdminAccount", "Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::111122223333:root" },
"Action": "kms:*", "Resource": "*" },
{ "Sid": "AppUse", "Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::111122223333:role/OrdersFnRole" },
"Action": ["kms:Decrypt", "kms:GenerateDataKey"], "Resource": "*",
"Condition": { "StringEquals": { "kms:EncryptionContext:app": "orders" } } }
]
}
The root statement lets IAM policies control access to the key. Without it, only principals named in the key policy have access. Cross-account use needs the key policy to allow the external account and the external identity's IAM policy to allow KMS actions.
How services use KMS
| Service | Option |
|---|---|
| S3 | SSE-KMS (with Bucket Keys) |
| EBS / RDS | KMS key at creation; snapshots inherit |
| DynamoDB | AWS owned (default), AWS managed or customer managed key |
| Lambda | Environment variable encryption; helper to encrypt in console |
| SQS / SNS | SSE-KMS |
| Secrets Manager / SSM SecureString | KMS-encrypted values |
Common errors
| Error | Cause |
|---|---|
AccessDeniedException on Decrypt | Key policy or IAM lacks kms:Decrypt; wrong encryption context |
ThrottlingException / request quota exceeded | Too many KMS calls (shared quota 5,500-30,000/s per Region by key type); use data key caching, S3 Bucket Keys |
DisabledException / KMSInvalidStateException | Key disabled or pending deletion |
InvalidCiphertextException | Wrong key, context or corrupted data |
CLI
aws kms create-key --description "orders data key"
aws kms create-alias --alias-name alias/app-data --target-key-id <key-id>
aws kms enable-key-rotation --key-id <key-id>
aws kms encrypt --key-id alias/app-data --plaintext fileb://secret.txt \
--encryption-context app=orders --query CiphertextBlob --output text
aws kms schedule-key-deletion --key-id <key-id> --pending-window-in-days 7
Always reference keys by alias in code so you can repoint to a new key without redeploying.
CloudHSM vs KMS
CloudHSM gives single-tenant HSMs under your sole control (FIPS 140-2 Level 3) for strict compliance; KMS is multi-tenant managed with deep service integration. KMS custom key stores can bridge the two.
Envelope encryption in code
import boto3, os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
kms = boto3.client("kms")
dk = kms.generate_data_key(KeyId="alias/app-data", KeySpec="AES_256",
EncryptionContext={"tenant": "t1"})
nonce = os.urandom(12)
ciphertext = AESGCM(dk["Plaintext"]).encrypt(nonce, b"secret payload", None)
stored = {"key": dk["CiphertextBlob"], "nonce": nonce, "data": ciphertext} # discard plaintext key
plain_key = kms.decrypt(CiphertextBlob=stored["key"], EncryptionContext={"tenant": "t1"})["Plaintext"]
Direct Encrypt handles only up to 4 KB, which is why larger data uses data keys. An encryption context is authenticated but not secret, appears in CloudTrail and must match on decryption.
| Key type | Managed by | Rotation | Cost |
|---|---|---|---|
| AWS owned | AWS, invisible | AWS | Free |
AWS managed (aws/s3) | AWS in your account | Yearly, automatic | Free key, pay for requests |
| Customer managed | You | Optional automatic (default 365 days, configurable) or manual | Monthly plus requests |
Key policies are the primary access control: without a key policy that trusts the account, IAM policies alone do not work. Grants delegate temporary use to services. Throttling errors (ThrottlingException) call for backoff, data key caching or the S3 bucket key feature, which cuts KMS calls for SSE-KMS. Scheduled key deletion has a 7 to 30 day waiting period.
Real World Example
A healthcare app stores patient PDFs in S3 and metadata in DynamoDB. Files are encrypted with SSE-KMS using a customer managed key with Bucket Keys enabled to reduce KMS calls by about 99%. For particularly sensitive fields the application uses the AWS Encryption SDK with an encryption context containing the tenant ID, so a ciphertext from one tenant cannot be decrypted under another tenant's context. The key policy limits kms:Decrypt to the application role, and CloudTrail alerts on any other principal.
Architecture Diagram
KMS protects a small data key; the data key encrypts the bulk data locally.
- 1The app requests a data key from KMS for a specific key and encryption context.
- 2KMS returns the plaintext data key and the same key encrypted under the KMS key.
- 3The app encrypts the data locally and wipes the plaintext key from memory.
- 4To read, the app asks KMS to decrypt the stored encrypted data key and decrypts the data.
Best Practices
- ✓Use envelope encryption (or the AWS Encryption SDK) for data over 4 KB.
- ✓Use encryption context to bind ciphertext to a tenant or purpose.
- ✓Reference keys by alias; enable rotation on customer managed keys.
- ✓Apply least privilege key policies; separate key administrators from key users.
- ✓Reduce KMS load with S3 Bucket Keys and data key caching.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Encrypt data larger than 4 KB -> GenerateDataKey / envelope encryption.
- KMS throttling from S3 -> S3 Bucket Keys.
- Key policy is mandatory; IAM alone is insufficient unless the key policy delegates to IAM.
- Audit who used a key -> CloudTrail (and encryption context in logs).
Finished this lesson?
0 of 46 lessons done · 0% of the course

