AWS KMS and Encryption for Developers: Key Types, Envelope Encryption, Encrypt Decrypt GenerateDataKey and Key Policies

AWS Developer Associate 55 min min read Updated: Nov 17, 2026 Advanced
AWS KMS and Encryption for Developers: Key Types, Envelope Encryption, Encrypt Decrypt GenerateDataKey and Key Policies
Advanced Topic 1 of 3

Why KMS

AWS Key Management Service (KMS) creates and controls cryptographic keys. The key material never leaves KMS unencrypted. You ask KMS to encrypt or decrypt, and every use is logged in CloudTrail. Most AWS services (S3, EBS, RDS, DynamoDB, SQS, Lambda environment variables, Secrets Manager) integrate with KMS.

Key Types (Exam Favorite)

TypeWho managesCostNotes
AWS owned keyAWS (shared across accounts)FreeDefault for some services (DynamoDB). Not visible to you. No CloudTrail or policy control
AWS managed keyAWS, in your account (alias aws/s3, aws/ebs)No monthly fee, pay per requestAutomatic rotation yearly. You cannot change its policy or delete it
Customer managed key (CMK)YouMonthly fee + per requestFull control: key policy, rotation, enable and disable, delete (7 to 30 days waiting period), cross-account sharing, multi-Region
Key specUse
Symmetric (AES-256-GCM)Default. Encrypt, decrypt, generate data keys. Used by AWS services
Asymmetric (RSA, ECC)Public key can be downloaded and used outside AWS. Encrypt/decrypt or sign/verify
HMAC keysGenerate and verify message authentication codes

The 4 KB Limit and Envelope Encryption

Encrypt and Decrypt work only on data up to 4 KB. For larger data use envelope encryption: KMS protects a small data key, and the data key encrypts the real data locally.

text ENCRYPT 1. Call KMS GenerateDataKey(KeyId) → returns Plaintext data key + Encrypted data key (ciphertext blob) 2. Encrypt your data locally (AES) with the plaintext data key 3. Delete the plaintext key from memory 4. Store: encrypted data + encrypted data key (together) DECRYPT 1. Call KMS Decrypt(encrypted data key) → plaintext data key 2. Decrypt the data locally with it, then discard the key
python import boto3, os from cryptography.hazmat.primitives.ciphers.aead import AESGCM kms = boto3.client("kms") KEY = "alias/orders-app" def encrypt(plaintext: bytes, context: dict): dk = kms.generate_data_key(KeyId=KEY, KeySpec="AES_256", EncryptionContext=context) nonce = os.urandom(12) ct = AESGCM(dk["Plaintext"]).encrypt(nonce, plaintext, None) return {"edk": dk["CiphertextBlob"], "nonce": nonce, "ct": ct} # plaintext key is not stored def decrypt(blob, context): key = kms.decrypt(CiphertextBlob=blob["edk"], EncryptionContext=context)["Plaintext"] return AESGCM(key).decrypt(blob["nonce"], blob["ct"], None) blob = encrypt(b"large secret document ...", {"orderId": "9002"}) print(decrypt(blob, {"orderId": "9002"}))
KMS APIPurpose
Encrypt / DecryptDirect encryption of up to 4 KB
GenerateDataKeyReturns plaintext + encrypted data key (for envelope encryption)
GenerateDataKeyWithoutPlaintextEncrypted data key only (use later by decrypting)
ReEncryptMove ciphertext to another key without exposing plaintext
Sign / VerifyAsymmetric signatures
GenerateRandomRandom bytes from a hardware source
CreateGrantDelegate limited use of a key to another principal
Use the AWS Encryption SDK The AWS Encryption SDK does envelope encryption for you (data key caching, message format, algorithm suites). Prefer it to hand-written crypto in production. Client-side encryption means AWS never sees plaintext.

Encryption Context

  • A set of non-secret key-value pairs bound to the ciphertext as additional authenticated data. Decryption fails unless the same context is supplied
  • Protects against using ciphertext in the wrong place and appears in CloudTrail, so it helps auditing
  • Use meaningful values like {"tenant": "acme", "table": "Orders"}

Key Policies, IAM and Grants

  • Every KMS key has a key policy. It is the primary access control. IAM policies work only if the key policy allows IAM to control access (the default key policy gives the account root kms:*, which enables IAM policies)
  • Cross-account use needs both: the key policy in the owner account allows the other account, and an IAM policy in the caller's account allows the action
  • Grants are temporary, programmatic permissions used by AWS services (for example EBS attaching an encrypted volume)
  • Use aliases (alias/orders-app) so code and policies do not change when you create new key material or a new key
json { "Sid": "AllowAppRoleUse", "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::111111111111:role/orders-app"}, "Action": ["kms:Decrypt", "kms:GenerateDataKey"], "Resource": "*", "Condition": {"StringEquals": {"kms:EncryptionContext:tenant": "acme"}} }
Common service-side permission pairsNeeded
Read an SSE-KMS object in S3s3:GetObject + kms:Decrypt
Write an SSE-KMS objects3:PutObject + kms:GenerateDataKey
Lambda reading encrypted env varskms:Decrypt on the key for the execution role
SNS publishing to a KMS-encrypted SQS queueSNS service needs kms:GenerateDataKey and kms:Decrypt in the key policy

Rotation, Deletion and Multi-Region

  • Automatic rotation (customer managed symmetric keys): choose 90 to 2,560 days (default 365). The key ID and ARN stay the same. Old key material is kept to decrypt old data. Asymmetric and imported keys do not rotate automatically (rotate manually and move the alias)
  • Deleting a key is irreversible and makes data unreadable. KMS enforces a 7 to 30 day waiting period. Prefer disabling first. Set a CloudWatch alarm on key use during the waiting period
  • Multi-Region keys share the same key id and material in several Regions, so you can encrypt in one Region and decrypt in another without cross-Region calls (DR, global tables, client-side encryption)
  • Imported key material (BYOK) is possible but you manage durability and rotation. CloudHSM-backed custom key stores exist for strict compliance

Limits and Performance

  • KMS has request quotas per second per Region (shared across keys for each operation type) and returns ThrottlingException when exceeded. Cache data keys (data key caching) and use S3 Bucket Keys to reduce calls
  • Calls to KMS add latency. Do not call KMS per record in hot paths. Encrypt a batch with one data key

KMS vs Other Services

NeedService
Manage encryption keys for AWS services and appsKMS
Dedicated single-tenant HSM you controlCloudHSM
Store passwords, API keys and rotate themSecrets Manager
Store config and small secrets cheaplySystems Manager Parameter Store
TLS certificatesACM

Practice Tasks

  1. Create a customer managed key with an alias and use encrypt and decrypt on a short string
  2. Implement envelope encryption for a 1 MB file with GenerateDataKey
  3. Add an encryption context and see decryption fail when it is wrong
  4. Allow another account's role to decrypt with a key policy plus IAM policy
  5. Disable the key and watch dependent S3 and Lambda operations fail, then re-enable it

Conclusion

KMS keeps key material safe and audits every use. Use customer managed keys for control, envelope encryption (GenerateDataKey) for data larger than 4 KB, encryption context for binding and auditing, key policies plus IAM for access (both sides for cross-account), aliases and rotation for maintenance, and multi-Region keys for DR.

Quick Summary: why KMS; key types; envelope encryption + code; API list; encryption context; policies and grants; rotation and deletion; limits; comparison.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators