SkillSprout
Chapter 8 · Lesson 2
Advanced
6 min read

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/month plus 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: GenerateDataKey returns 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: root delegating 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

ApproachData sizeNetworkUse
Encrypt / DecryptUp to 4 KBEvery operation calls KMSSmall secrets, data keys
Envelope (GenerateDataKey)Any sizeOne KMS call per objectFiles, large payloads

Envelope encryption flow in Python

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

json
{
  "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

ServiceOption
S3SSE-KMS (with Bucket Keys)
EBS / RDSKMS key at creation; snapshots inherit
DynamoDBAWS owned (default), AWS managed or customer managed key
LambdaEnvironment variable encryption; helper to encrypt in console
SQS / SNSSSE-KMS
Secrets Manager / SSM SecureStringKMS-encrypted values

Common errors

ErrorCause
AccessDeniedException on DecryptKey policy or IAM lacks kms:Decrypt; wrong encryption context
ThrottlingException / request quota exceededToo many KMS calls (shared quota 5,500-30,000/s per Region by key type); use data key caching, S3 Bucket Keys
DisabledException / KMSInvalidStateExceptionKey disabled or pending deletion
InvalidCiphertextExceptionWrong key, context or corrupted data

CLI

bash
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

python
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 typeManaged byRotationCost
AWS ownedAWS, invisibleAWSFree
AWS managed (aws/s3)AWS in your accountYearly, automaticFree key, pay for requests
Customer managedYouOptional automatic (default 365 days, configurable) or manualMonthly 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

Envelope encryption
Architecture
AWS Cloud
Application
KMS keynever leaves KMS
Encrypt locallyAES-GCM
S3 objectciphertext + EDK

KMS protects a small data key; the data key encrypts the bulk data locally.

  1. 1The app requests a data key from KMS for a specific key and encryption context.
  2. 2KMS returns the plaintext data key and the same key encrypted under the KMS key.
  3. 3The app encrypts the data locally and wipes the plaintext key from memory.
  4. 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