AWS KMS
LearningTree Β· AWS Security Β· Deep Dive

AWS KMS β€”
Key Management Service

The complete guide to encryption and key management in AWS. From understanding basic cryptography to designing multi-account encrypted architectures β€” KMS is the foundation of data protection.

8 Chapters Beginner β†’ Professional Exam Ready Architecture Patterns

⚑ KMS in 30 Seconds

  • KMS manages encryption keys β€” it does NOT store your data, it protects the keys that encrypt your data
  • Uses envelope encryption: KMS generates a data key β†’ you encrypt data locally β†’ KMS encrypts the data key
  • Integrates natively with 100+ AWS services (S3, EBS, RDS, Lambda, DynamoDB…)
  • Key policies control WHO can use and manage keys β€” separate from IAM policies
  • Keys never leave KMS unencrypted β€” they are processed inside FIPS 140-2 validated hardware
01
Chapter One

What is Encryption & KMS

The Problem β€” Why Encryption Matters Introductory

Every piece of data in the cloud faces threats: unauthorized access, insider threats, compliance requirements, and data breaches. Encryption is the last line of defense β€” even if someone gains access to your storage, encrypted data is useless without the key.

🚨

Without Encryption

  • Data readable by anyone with storage access
  • Failed audits and compliance violations
  • One breach exposes everything
πŸ”

With Encryption

  • Data is meaningless without the decryption key
  • Meets compliance (HIPAA, PCI-DSS, SOC2)
  • Breach = access to ciphertext only
πŸ”‘

With KMS

  • Keys managed centrally and securely
  • Automatic rotation and audit trail
  • Fine-grained access control on keys
Encryption at Rest vs In Transit Introductory

AWS encryption operates in two domains:

Encryption at Rest

Data is encrypted while stored on disk, in databases, or in object storage.

  • S3 objects on disk
  • EBS volumes
  • RDS database files
  • DynamoDB tables

Protects: Physical theft, unauthorized disk access, decommissioned hardware

Encryption in Transit

Data is encrypted while moving between systems over a network.

  • HTTPS (TLS) for API calls
  • TLS between services
  • VPN tunnels
  • SSH connections

Protects: Eavesdropping, man-in-the-middle, network sniffing

Key Distinction

KMS primarily handles encryption at rest. Encryption in transit is handled by TLS/SSL certificates (ACM). They complement each other β€” a complete system uses both.

What AWS KMS Actually Does Core

A critical mental model shift:

Common Misconception

"KMS encrypts my data" β€” This is technically wrong for most use cases. KMS manages keys, not data. Your data is encrypted locally using a data key that KMS generated and protects.

What KMS actually provides:

  • Key generation β€” creates cryptographic keys inside FIPS 140-2 Level 2 hardware security modules (HSMs)
  • Key storage β€” keys never leave the HSM unencrypted
  • Key rotation β€” automatically rotates keys annually (you keep using the same key ID)
  • Access control β€” key policies + IAM policies determine who can encrypt/decrypt
  • Audit trail β€” every key usage logged in CloudTrail
  • Envelope encryption β€” generates data keys for local encryption (the real workhorse)
Mental Model β€” The Vault & Master Key Core
Real World
  • A bank vault holds safety deposit boxes
  • The master key is held by the bank manager and never leaves the vault
  • You get a copy key to lock your box
  • The copy key itself is stored inside the vault (encrypted by master key)
  • To use your box: present ID β†’ bank retrieves your copy key β†’ you access data
AWS KMS
  • KMS = vault (FIPS 140-2 HSMs)
  • KMS Key (CMK) = the master key that never leaves KMS
  • Data Key = the copy key used to encrypt your actual data
  • Encrypted data key stored alongside your ciphertext
  • To decrypt: call KMS API β†’ KMS decrypts data key β†’ you decrypt data locally
The Core Insight

KMS primarily manages encryption keys, not large data directly. It generates, stores, rotates, and controls access to keys β€” the actual data encryption happens locally using those keys.

IAM Controls Access, KMS Controls Encryption Core
ConcernServiceQuestion Answered
Authentication & AuthorizationIAMWHO can access WHAT resources?
Data ProtectionKMSHOW is data protected at rest?
Key AccessKMS + IAMWHO can use encryption keys?

They work together: IAM might grant you access to an S3 bucket, but if the objects are encrypted with a KMS key you don't have permission to use, you still can't read the data.

Diagram 1 β€” Concept: The Encryption Flow Introductory
Encryption β€” Plaintext to Ciphertext
PLAINTEXT "Hello World" ENCRYPTION Algorithm (AES-256) + Key KEY CIPHERTEXT "x8f2...b4a1" + Key = Plaintext
Fundamental encryption: plaintext + key β†’ ciphertext. Without the key, ciphertext is unreadable.
Diagram 2 β€” AWS: KMS in the Ecosystem Core
KMS β€” Central Key Authority for AWS Services
AWS KMS Key Management S3 EBS RDS Lambda DynamoDB EC2 All services request keys from KMS β†’ encrypt data locally β†’ never expose plaintext keys
KMS acts as the central key authority. Services request data keys, encrypt data locally, and store encrypted data alongside the encrypted data key.
Diagram 3 β€” Architecture: Complete Encrypted Stack In-Depth
Production Architecture β€” Encryption at Every Layer
Client (HTTPS/TLS) in-transit encryption Application Layer (EC2 / Lambda / ECS) Calls KMS to get/decrypt data keys GenerateDataKey KMS HSM-backed Encrypted Storage Layer (at-rest encryption) S3 (SSE-KMS) EBS (encrypted) RDS (encrypted) DynamoDB SQS encrypted data + encrypted key CloudTrail Key usage audit Defense in Depth TLS in transit + KMS at rest + IAM access control + CloudTrail audit = complete protection Even if one layer fails, data remains protected by the others
Real production setup: TLS protects data in transit, KMS protects data at rest, IAM controls who can access, CloudTrail logs everything.
KMS β€” Key Properties at a Glance Core
PropertyDetail
RegionalKMS keys are region-specific. A key in us-east-1 cannot be used in eu-west-1 (unless multi-region key)
FIPS 140-2 Level 2All keys processed inside validated HSMs β€” keys never leave unencrypted
4 KB limitKMS can directly encrypt up to 4 KB of data. For anything larger β†’ envelope encryption
Pricing$1/month per key + $0.03 per 10,000 API calls
Key Deletion7–30 day waiting period (cannot be undone after deletion)
Automatic RotationEvery 365 days for customer managed keys (opt-in). Key ID stays the same.
CloudTrail IntegrationEvery Encrypt, Decrypt, GenerateDataKey call is logged
Critical β€” The 4 KB Limit

KMS cannot directly encrypt files, database records, or any data larger than 4 KB. This is by design β€” it forces you to use envelope encryption, which is more secure and performant. This is why Chapter 04 (Envelope Encryption) is the most important chapter in this guide.

Exam Tips β€” Chapter 01
  • "Encrypt data at rest" β†’ think KMS
  • "Encrypt data in transit" β†’ think TLS/ACM
  • "Meet compliance for encryption key management" β†’ KMS + CloudTrail audit
  • "Regional service" β€” keys don't replicate by default (multi-region keys are the exception)
  • "FIPS 140-2" β€” KMS uses validated HSMs; CloudHSM uses Level 3 (dedicated)
  • "4 KB limit" β€” forces envelope encryption pattern
Chapter 01 Summary β€” What is Encryption & KMS
  • Encryption transforms readable data (plaintext) into unreadable data (ciphertext) using a key.
  • At rest = stored data. In transit = data moving on the network.
  • KMS manages keys, not data. It generates, stores, rotates, and controls access to encryption keys.
  • Keys live inside FIPS 140-2 Level 2 HSMs and never leave unencrypted.
  • KMS can only directly encrypt up to 4 KB β€” larger data uses envelope encryption.
  • Every key operation is logged in CloudTrail for audit.
  • KMS keys are regional by default.
  • IAM controls who can access resources; KMS controls how data is protected.
Chapter 01 β€” Key Takeaway

KMS is not an encryption engine for your data β€” it's a key management vault. It generates keys, protects them in hardware, controls who can use them, and logs every usage. The actual encryption happens locally using keys KMS provides.

KMS vs CloudHSM vs ACM β€” When to Use Which Core

Three AWS services handle encryption-related tasks, but they serve very different purposes:

ServicePurposeKey CharacteristicTypical Use Case
KMSManage encryption keys for AWS servicesKeys never leave HSMs (FIPS 140-2 Level 2)S3, EBS, RDS encryption at rest
CloudHSMDedicated, single-tenant HSMYou control the HSM (FIPS 140-2 Level 3)Regulatory requiring dedicated hardware
ACMManage TLS/SSL certificatesAutomates certificate provisioning & renewalHTTPS for CloudFront, ALB, API Gateway
Quick Rule

KMS = data at rest encryption. ACM = encryption in transit (TLS certificates). CloudHSM = when you need your own dedicated HSM hardware for regulatory compliance. Example: "Encrypt data in S3 AND terminate HTTPS at ALB" β†’ KMS for S3 + ACM for the TLS certificate.

02
Chapter Two

KMS Core Concepts

KMS Key Types Core

KMS has three categories of keys based on who manages them and who owns them. Understanding this distinction is critical for exams and architecture decisions.

πŸ›οΈ

AWS Owned Keys

  • Managed entirely by AWS
  • Shared across many accounts (you never see them)
  • Free β€” no cost
  • No CloudTrail logging
  • Used by default: DynamoDB, S3 (SSE-S3)
  • You cannot view, rotate, or control
πŸ”‘

AWS Managed Keys

  • Created in YOUR account by AWS services
  • Named aws/service-name (e.g., aws/s3, aws/ebs)
  • Free (no monthly fee)
  • Auto-rotated every year
  • Visible in your KMS console
  • You cannot change key policy or delete
πŸ‘‘

Customer Managed Keys (CMKs)

  • Created and controlled by YOU
  • Full control: policies, rotation, deletion
  • $1/month per key
  • Optional automatic rotation (yearly)
  • Cross-account sharing possible
  • Can be imported or generated by KMS
Architecture Decision

Use AWS Managed Keys for simple "enable encryption" cases. Use Customer Managed Keys when you need cross-account access, custom key policies, granular CloudTrail audit, or compliance that requires you to control key lifecycle.

Key Types β€” Full Comparison Core
FeatureAWS OwnedAWS ManagedCustomer Managed
Visible in your accountNoYesYes
Key policy controlNoNo (view only)Full control
RotationVaries (AWS decides)Every year (automatic)Optional (yearly, on-demand)
CloudTrail loggingNoYesYes
Cross-account useNoNoYes (via key policy)
CostFreeFree (API charges only)$1/month + API charges
DeletionNot possibleNot possibleYou can schedule (7-30 day wait)
AliasN/Aaws/service-nameCustom alias you define
Key Material Origin In-Depth

When you create a Customer Managed Key, you choose where the key material comes from:

KMS (default)
KMS generates AND stores the key material inside its HSMs. Simplest option β€” AWS handles everything.
External (BYOK)
You generate key material externally and import it into KMS. You're responsible for durability and availability of the original. Useful for compliance that requires key generation in your own HSM.
Custom Key Store (CloudHSM)
Key material generated AND stored in your dedicated CloudHSM cluster. KMS acts as a front-end. Maximum control β€” FIPS 140-2 Level 3. Required for certain government/financial regulations.
External Key Store (XKS)
Key material stored in your own key manager outside AWS entirely. KMS calls your external endpoint for every operation. Ultimate sovereignty β€” but adds latency and single-point-of-failure risk.
When to Use What

99% of workloads: use KMS-generated key material. Compliance-driven: use External (BYOK) or Custom Key Store. Data sovereignty laws requiring keys outside AWS: External Key Store (XKS).

Key Identifiers β€” How to Reference a Key Core

Every KMS key can be referenced in multiple ways:

Key ID
A UUID like 1234abcd-12ab-34cd-56ef-1234567890ab. Unique within a region.
Key ARN
arn:aws:kms:us-east-1:123456789012:key/1234abcd-... β€” fully qualified, required for cross-account use.
Alias Name
alias/my-app-key β€” a friendly name. Can be updated to point to a different key (useful for rotation).
Alias ARN
arn:aws:kms:us-east-1:123456789012:alias/my-app-key
Best Practice

Always use aliases in application code. When you rotate to a new key, just update the alias β€” no code change needed. Use Key ARN in cross-account policies.

Key Alias Best Practices β€” Production Strategy In-Depth

Aliases decouple your application from specific key versions. This is critical for zero-downtime key rotation:

  1. Create alias: alias/prod-database-key
    Point it to your current CMK (my-key-v1). All application code references the alias, never the key ID.
  2. When rotating: create my-key-v2
    Generate a new CMK alongside the old one. Both exist in parallel.
  3. Update alias to point to v2
    Call UpdateAlias β€” the alias now resolves to the new key. Application code doesn't change.
  4. Old key remains for decryption
    Existing ciphertext still encrypted with v1. Keep v1 enabled until all data is re-encrypted or expired.
Naming Convention
alias/env/service/purpose β€” e.g., alias/prod/database/encryption, alias/dev/s3/backup, alias/finance/payroll-key
Cross-Account Limit
You cannot use an alias from another account. Always use the full Key ARN for cross-account references.
Alias Limits
Maximum 50 aliases per key (soft limit). Aliases are regional β€” create in each region where the key is used.
Key States & Lifecycle Core

A KMS key goes through distinct states during its lifecycle:

KMS Key Lifecycle States
Pending Import (BYOK only) Enabled Ready to use Disabled Cannot use Pending Deletion 7-30 day wait cancel Deleted IRREVERSIBLE Enabled ↔ Disabled is reversible. Once deleted, all data encrypted by this key is PERMANENTLY lost.
Key states are managed via KMS API: EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion
Critical β€” Key Deletion is Catastrophic

When a KMS key is deleted, all data encrypted by that key becomes permanently unrecoverable. There is no backup, no recovery, no support ticket that can help. The 7-30 day waiting period exists specifically to prevent accidents. Always set up CloudWatch alarms on ScheduleKeyDeletion events.

Key Rotation Core

Rotation replaces the backing key (the actual cryptographic material) while keeping the same Key ID and ARN. Old backing keys are retained forever so old ciphertext can still be decrypted.

How Rotation Works
  • KMS generates new backing key material
  • New encryptions use the new backing key
  • Old backing keys kept for existing decryptions
  • Key ID, ARN, alias β€” all stay the same
  • Zero code changes required
Rotation Options
  • Automatic: every 365 days (opt-in for CMKs, always on for AWS managed)
  • On-demand: trigger rotation manually via API/console
  • Manual: create a new key and update your alias to point to it (needed for imported key material)
Rotation Does NOT Re-encrypt Data

Key rotation only affects new encryption operations. Existing ciphertext remains encrypted with the old backing key. If compliance requires re-encryption, you must do it yourself (decrypt β†’ re-encrypt with new key).

KMS API Operations Core

The key API calls you'll encounter constantly:

API CallWhat It DoesData Limit
EncryptEncrypts up to 4 KB of plaintext directly with a KMS key4 KB
DecryptDecrypts ciphertext that was encrypted by KMS4 KB
GenerateDataKeyReturns plaintext data key + encrypted copy. For envelope encryption.Generates key for any size data
GenerateDataKeyWithoutPlaintextReturns ONLY the encrypted data key (for pre-staging)β€”
ReEncryptDecrypts ciphertext then re-encrypts under a different key β€” without exposing plaintext4 KB
CreateGrantDelegates key permissions to another principal temporarilyβ€”
GenerateRandomReturns cryptographically secure random bytes (1-1024 bytes)1024 bytes
Diagram β€” KMS API Call Flow Core
Direct Encrypt / Decrypt Flow (≀ 4 KB)
Your Application SDK / CLI / Console kms:Encrypt(plaintext, keyId) AWS KMS 1. Validate permissions 2. Encrypt in HSM 3. Return ciphertext ciphertext blob CloudTrail Logs every call For data ≀ 4 KB: application sends plaintext directly to KMS. KMS encrypts inside HSM and returns ciphertext. For data > 4 KB β†’ use GenerateDataKey (envelope encryption β€” Chapter 04)
Direct encryption is simple but limited to 4 KB. Most real-world usage is via GenerateDataKey (envelope encryption).
Grants β€” Delegated Key Permissions In-Depth

Grants are an alternative to key policies for temporary, programmatic permission delegation:

When to Use Grants

  • AWS services need temporary key access (e.g., EBS snapshot copy)
  • You want to delegate without modifying key policy
  • Time-limited access for a specific operation
  • Programmatic β€” created via API, no manual policy edit

Grant Properties

  • Grantee Principal: who receives the permission
  • Operations: what they can do (Encrypt, Decrypt…)
  • Constraints: optional conditions (encryption context)
  • Retiring Principal: who can revoke the grant
Grants vs Key Policies

Key policies = permanent, declarative, JSON-based. Grants = temporary, programmatic, API-based. Many AWS services (EBS, RDS) use grants internally when they need key access for specific operations.

Encryption Context β€” AAD for KMS In-Depth

Encryption context is a set of key-value pairs (non-secret) that are cryptographically bound to the ciphertext. Think of it as an additional authentication check.

  1. Encrypt with context

    kms:Encrypt(plaintext, keyId, {"department": "finance", "project": "payroll"})

  2. Context is bound to ciphertext

    The context is included as Additional Authenticated Data (AAD). It's NOT encrypted β€” but it IS required for decryption.

  3. Decrypt must provide same context

    kms:Decrypt(ciphertext, {"department": "finance", "project": "payroll"}) β€” if context doesn't match, decryption FAILS.

  4. Logged in CloudTrail

    Encryption context appears in CloudTrail logs β€” perfect for auditing WHO encrypted WHAT for WHICH purpose.

Why Encryption Context Matters

It prevents ciphertext from being used out of context. Even if an attacker has the ciphertext AND decrypt permissions, they must know the exact encryption context. It's also valuable for CloudTrail audit β€” you can see what was encrypted, not just that encryption happened.

Encryption Context β€” Real-World Usage Patterns In-Depth

Encryption context is cryptographically bound to the ciphertext AND logged in CloudTrail. Here's how production teams use it:

Multi-Tenant SaaS

{"tenantId": "tenant-12345", "customerId": "cust-67890"}

  • CloudTrail shows which tenant's data accessed
  • Prevents cross-tenant decryption
  • Same CMK shared across tenants

Environment Isolation

{"environment": "production", "service": "payment"}

  • Same CMK for dev/prod
  • Context prevents prod keys in dev
  • Key policy condition enforces

Healthcare Compliance

{"patientId": "PAT-456", "recordType": "medical-history"}

  • Complete audit trail per patient
  • WHO accessed WHICH data
  • HIPAA compliance evidence

S3 Automatic Context

{"aws:s3:arn": "arn:aws:s3:::bucket/key"}

  • S3 adds this automatically (SSE-KMS)
  • CloudTrail shows exact object
  • Reduced with S3 Bucket Keys (bucket ARN instead)
Best Practice

Always include at least one context key-value pair. It costs nothing, adds zero latency, and dramatically improves auditability. Use it for tenant isolation, environment separation, and compliance evidence.

Key Spec & Key Usage Core

When creating a KMS key, you specify what it can do:

Key UsageDescriptionKey Specs Available
ENCRYPT_DECRYPTSymmetric encryption. Most common β€” used by all AWS service integrations.SYMMETRIC_DEFAULT (AES-256-GCM)
SIGN_VERIFYDigital signatures. Asymmetric only.RSA_2048..4096, ECC_NIST_P256..P521, SM2
GENERATE_VERIFY_MACHMAC operations.HMAC_224..512
KEY_AGREEMENTDerive shared secrets (ECDH). New in 2024.ECC_NIST_P256..P521, SM2
Important β€” Key Usage is Immutable

Once you create a key with a specific usage (e.g., ENCRYPT_DECRYPT), you cannot change it. You'd need to create a new key. Plan your key strategy upfront.

Multi-Region Keys In-Depth

By default, KMS keys are regional. Multi-Region keys are replicas of the same key in multiple regions β€” same key material, same key ID (with mrk- prefix).

Use Cases

  • Encrypt in one region, decrypt in another
  • DynamoDB global tables with encryption
  • S3 cross-region replication of encrypted objects
  • Disaster recovery β€” decrypt in failover region

Not Recommended When

  • Data residency laws require separate keys per region
  • You want independent key policies per region
  • Simple single-region workloads (adds complexity)
  • You need different key material per region
Multi-Region Key β€” Primary & Replicas
PRIMARY KEY mrk-123abc... (us-east-1) REPLICA (eu-west-1) Same key material REPLICA (ap-southeast-1) Same key material REPLICA (us-west-2) Same key material
Multi-region keys share identical key material. Encrypt in any region, decrypt in any other. Independent key policies per region.
Exam Tips β€” Chapter 02
  • "Cannot change key policy" β†’ AWS Managed Key. Need control? Use Customer Managed Key.
  • "Cross-account encryption" β†’ must use Customer Managed Key + key policy granting access
  • "Key never leaves AWS" β†’ KMS default. "Key material outside AWS" β†’ External Key Store (XKS)
  • "FIPS 140-2 Level 3" β†’ CloudHSM (not KMS). KMS is Level 2.
  • "Encrypt in us-east-1, decrypt in eu-west-1" β†’ Multi-Region Key
  • "Scheduled deletion" β†’ 7-30 days waiting period. Can be cancelled.
  • "Rotation doesn't re-encrypt data" β†’ correct. Old backing key retained for old ciphertext.
  • "Encryption context" β†’ required at decrypt time if provided at encrypt time. Logged in CloudTrail.
  • GenerateDataKey β†’ envelope encryption (data > 4 KB). Encrypt β†’ direct (≀ 4 KB).
Chapter 02 Summary β€” Core Concepts
  • Three key types: AWS Owned (invisible, free), AWS Managed (visible, no control), Customer Managed (full control, $1/mo).
  • Key material origin: KMS-generated (default), External (BYOK), Custom Key Store (CloudHSM), External Key Store (XKS).
  • Key identifiers: Key ID, Key ARN, Alias Name, Alias ARN. Use aliases in code.
  • Key states: Enabled β†’ Disabled β†’ Pending Deletion β†’ Deleted (irreversible).
  • Key rotation: replaces backing material, retains old for decryption, same Key ID.
  • API operations: Encrypt (≀4KB), Decrypt, GenerateDataKey, ReEncrypt, CreateGrant.
  • Grants: temporary, programmatic key permission delegation (used by AWS services internally).
  • Encryption context: key-value pairs bound to ciphertext β€” must match at decrypt time.
  • Multi-Region keys: same key material across regions β€” encrypt anywhere, decrypt anywhere.
Chapter 02 β€” Key Takeaway

Customer Managed Keys give you full control over policies, rotation, and cross-account access. Every key has a lifecycle (enabled β†’ deleted), and deletion is irreversible. Use aliases for flexibility, encryption context for audit, and understand that rotation only affects new encryptions.

Chapter 02 of 08
03
Chapter Three
Symmetric vs Asymmetric Keys

KMS supports two fundamental cryptographic key types β€” symmetric (one shared secret) and asymmetric (public + private key pair). Understanding when and why to choose each is critical for every AWS architecture decision.

Symmetric Keys β€” Single-Secret Encryption Core

A symmetric KMS key generates a single 256-bit AES-GCM key. The same key encrypts and decrypts data. The plaintext key never leaves KMS unencrypted β€” all encrypt/decrypt operations happen inside the HSM boundary.

πŸ”‘

How Symmetric Works

  • One key β€” used for both encrypt & decrypt
  • AES-256-GCM algorithm
  • Key material stays in HSM hardware
  • Encrypt up to 4 KB directly via API
  • For larger data β†’ envelope encryption (Ch04)
βœ…

When to Use Symmetric

  • Encrypting data at rest (S3, EBS, RDS, DynamoDB)
  • All AWS service integrations (default)
  • Envelope encryption with data keys
  • When both encrypt/decrypt happen inside AWS
  • Highest performance & lowest cost
Key Fact

Every KMS key you create is symmetric by default. Over 99% of AWS service integrations use symmetric keys β€” if you're unsure, choose symmetric.

Asymmetric Keys β€” Public/Private Pairs Core

An asymmetric KMS key creates a mathematically linked pair: a private key (stays in HSM) and a public key (downloadable). Different algorithms serve different purposes.

Key SpecAlgorithmUse CaseMax Data Size
RSA_2048RSAES_OAEP_SHA_256Encrypt / Decrypt214 bytes
RSA_3072RSAES_OAEP_SHA_256Encrypt / Decrypt342 bytes
RSA_4096RSAES_OAEP_SHA_256Encrypt / Decrypt470 bytes
RSA_2048RSASSA_PSS / PKCS1Sign / Verifyβ€”
ECC_NIST_P256ECDSA_SHA_256Sign / Verifyβ€”
ECC_NIST_P384ECDSA_SHA_384Sign / Verifyβ€”
ECC_NIST_P521ECDSA_SHA_512Sign / Verifyβ€”
ECC_SECG_P256K1ECDSA_SHA_256Sign / Verify (blockchain)β€”
SM2 (China)SM2DSA / SM2PKESign or Encryptβ€”
πŸ”

Asymmetric for Encryption

  • Public key encrypts (anyone can)
  • Private key decrypts (only KMS)
  • Useful when encryptor has no AWS credentials
  • External clients, IoT devices, mobile apps
  • Limited by RSA max data size
✍️

Asymmetric for Signing

  • Private key signs (KMS does this)
  • Public key verifies (anyone can)
  • JWT tokens, code signing, document signing
  • External verification without AWS API calls
  • ECC preferred for performance; RSA for compatibility
Diagram 3-1 Β· Symmetric vs Asymmetric β€” Operation Flow
SYMMETRIC (AES-256) πŸ”‘ Same Key Encrypt(plaintext) Decrypt(ciphertext) AWS KMS HSM Key never leaves this boundary Both parties must have KMS API access ASYMMETRIC (RSA / ECC) 🌐 Public Key πŸ”’ Private Key Encrypt (anyone) Decrypt (KMS only) HSM Boundary Private key locked here External Client No AWS creds needed Public key downloadable β†’ use outside AWS
Left: Symmetric β€” one key, both parties need KMS access Β· Right: Asymmetric β€” public key distributed freely
Key Usage β€” ENCRYPT_DECRYPT vs SIGN_VERIFY Core

When creating an asymmetric key, you must choose its KeyUsage. A key can only be used for one purpose β€” this is immutable after creation.

ENCRYPT_DECRYPT
Key can encrypt/decrypt data. Available for symmetric (AES) and asymmetric (RSA) keys. Not available for ECC keys.
SIGN_VERIFY
Key can create/verify digital signatures. Available for asymmetric keys only (RSA, ECC). Used for code signing, JWT, document integrity.
GENERATE_VERIFY_MAC
Key generates/verifies HMACs. Symmetric only (HMAC_224/256/384/512). Used for message authentication codes β€” ensures data integrity + authenticity.
KEY_AGREEMENT
Key participates in key agreement protocols (ECDH). ECC keys only. Two parties derive a shared secret without transmitting it.
Immutable Decision

KeyUsage and KeySpec are set at creation and cannot be changed. If you need encryption AND signing, you need two separate keys.

HMAC Keys β€” Message Authentication Deep

KMS supports symmetric HMAC keys for generating and verifying Hash-based Message Authentication Codes. Unlike encryption, HMAC doesn't hide data β€” it proves integrity and authenticity.

HMAC_SHA_256

  • 256-bit key
  • Most common choice
  • API token validation

HMAC_SHA_384

  • 384-bit key
  • Higher security margin
  • Financial protocols

HMAC_SHA_512

  • 512-bit key
  • Maximum security
  • Critical system integrity

Use cases for KMS HMAC: validating API tokens, verifying webhook signatures, secure session cookies, license key validation β€” anywhere you need "was this data produced by someone who has the key?" without encrypting the data itself.

Diagram 3-2 Β· Digital Signing & Verification Flow
SIGNER (AWS Account) Document or message hash KMS Sign API Private key in HSM ✍️ Signature transmit VERIFIER (External / Any Party) Document Signature 🌐 Public Key downloaded from KMS βœ“ Verified / βœ— Invalid
Signer uses private key (never leaves HSM) Β· Verifier uses downloadable public key (no AWS access needed)
Decision Matrix β€” Choosing the Right Key Type Core
ScenarioKey TypeKey SpecWhy
S3 server-side encryptionSymmetricSYMMETRIC_DEFAULTAWS service integration β€” only option
EBS volume encryptionSymmetricSYMMETRIC_DEFAULTData at rest β€” envelope encryption
IoT device sending encrypted dataAsymmetricRSA_2048Device has public key, no AWS creds
JWT token signing (Lambda)AsymmetricECC_NIST_P256Fast signing, external verification
Code artifact signingAsymmetricRSA_4096Wide compatibility, strong security
API webhook validationHMACHMAC_SHA_256Prove origin without encryption
Cross-account data sharingSymmetricSYMMETRIC_DEFAULTGrant decrypt access to other account
Blockchain transaction signingAsymmetricECC_SECG_P256K1secp256k1 standard for crypto chains
TLS certificate private keyAsymmetricRSA_2048ACM integration with custom key store
Architecture Pattern β€” Hybrid Signing System Deep

A common production pattern combines symmetric keys for bulk encryption with asymmetric keys for signing artifacts:

  1. Build system produces artifact
    CI/CD pipeline compiles code, generates container image or deployment package.
  2. Sign artifact hash with asymmetric key
    Call kms:Sign with artifact SHA-256 digest. KMS uses private ECC/RSA key inside HSM.
  3. Store artifact + signature
    Upload artifact to S3 (encrypted with symmetric CMK via SSE-KMS) and attach signature as metadata.
  4. Consumer downloads & verifies
    Deployment system downloads artifact, retrieves public key, verifies signature locally β€” no KMS API call needed.
  5. Deploy with confidence
    Verified artifact is decrypted (KMS Decrypt via IAM role) and deployed. Tamper-proof supply chain.
Diagram 3-3 Β· Key Type Selection Flowchart
What do you need? Encrypt / Decrypt Within AWS? External encryptor? SYMMETRIC AES-256-GCM ASYMMETRIC RSA RSA_2048–4096 Sign / Verify Performance? Compatibility? ECC P256 / P384 / P521 RSA RSA_2048–4096 Integrity / MAC HMAC SHA-256/384/512 QUICK RULE AWS service integration β†’ Symmetric Β· External party involved β†’ Asymmetric Β· Prove integrity only β†’ HMAC ECC = faster & smaller signatures Β· RSA = wider compatibility Β· P256K1 = blockchain
Decision tree for selecting the correct KMS key type and algorithm
Limitations & Gotchas Deep
⚠️

Asymmetric Limitations

  • Cannot use with AWS service integrations (S3, EBS, RDS)
  • RSA encryption limited to small payloads (214–470 bytes)
  • No automatic key rotation (must manually create new key)
  • Cannot generate data keys (no GenerateDataKey)
  • Cannot use encryption context
  • Higher API latency than symmetric operations
πŸ’‘

Symmetric Limitations

  • Plaintext key never exported β€” both sides need KMS access
  • Cannot be used for digital signatures
  • Public key concept doesn't exist
  • Direct encrypt limited to 4 KB
  • Cross-region: must re-encrypt or use multi-region keys
🎯 Exam Tips β€” Symmetric vs Asymmetric
  • "External party needs to encrypt" β†’ Asymmetric RSA (public key distributed, no AWS creds needed)
  • "AWS service encryption (S3, EBS, RDS)" β†’ Always symmetric. Asymmetric keys CANNOT integrate.
  • "Verify signature without AWS access" β†’ Asymmetric (download public key, verify locally)
  • "Rotate asymmetric key" β†’ Manual process. Create new key, distribute new public key, retire old.
  • "HMAC" in question β†’ Symmetric HMAC key, GENERATE_VERIFY_MAC usage.
  • "Envelope encryption" β†’ Symmetric only. GenerateDataKey not available for asymmetric.
  • "Encrypt large data outside AWS" β†’ Hybrid: use asymmetric to encrypt a symmetric data key, then use AES locally.
Real-World Analogy

Symmetric key = a shared safe combination. Both parties must know the combo (have KMS access).

Asymmetric key = a padlock. Anyone can lock it (public key), but only the owner has the key to open it (private key in HSM).

AWS Translation

Symmetric: both encrypt-side and decrypt-side call KMS API (need IAM permissions).

Asymmetric: encrypt-side uses downloaded public key (no AWS needed); decrypt-side calls KMS (private key never leaves).

Chapter 03 Summary β€” Symmetric vs Asymmetric
  • Symmetric (AES-256): One key, both sides need KMS access. Default for all AWS service integrations. Fast, cheap, supports envelope encryption.
  • Asymmetric (RSA/ECC): Key pair β€” public (downloadable) + private (HSM-locked). Use when external parties participate.
  • KeyUsage is immutable: ENCRYPT_DECRYPT, SIGN_VERIFY, GENERATE_VERIFY_MAC, or KEY_AGREEMENT. One key = one purpose.
  • HMAC keys: Symmetric keys for message authentication β€” prove integrity without encryption.
  • Asymmetric rotation: Manual only. Must create new key and redistribute public key.
  • ECC vs RSA: ECC = smaller/faster signatures; RSA = wider compatibility + encryption support.
  • AWS services (S3, EBS, RDS): Only symmetric keys work. No exceptions.
  • Hybrid pattern: Asymmetric to protect a symmetric data key β†’ AES encrypts bulk data locally.
Chapter 03 β€” Key Takeaway

Choose symmetric for AWS-native encryption (99% of cases). Choose asymmetric when an external party must encrypt or verify without AWS credentials. The decision is permanent β€” KeyUsage and KeySpec cannot be changed after creation.

Chapter 03 of 08
04
Chapter Four
Envelope Encryption

Envelope encryption is the single most important concept in KMS. It's how AWS encrypts terabytes of data while only using KMS for a tiny 256-bit key. Master this and you understand every AWS encryption integration.

Why This Matters

KMS can only encrypt up to 4 KB directly. Every real-world workload (files, databases, volumes) uses envelope encryption β€” encrypting a data key with KMS, then using that data key locally. This is not optional knowledge β€” it's foundational.

The Problem β€” Why Not Encrypt Everything Directly? Beginner

If KMS can only encrypt 4 KB at a time, how does AWS encrypt a 1 TB EBS volume? Sending every block to KMS would be:

🐌

Impossibly Slow

  • Network round-trip per 4 KB block
  • 1 TB = 262 million API calls
  • Days to encrypt a single volume
πŸ’Έ

Absurdly Expensive

  • $0.03 per 10,000 requests
  • 262M calls = $786 per volume
  • Multiply by hundreds of volumes
🚫

Rate Limited

  • KMS quota: 5,500–30,000 req/sec
  • Would throttle instantly
  • All other apps blocked too

The solution: Don't send the data to KMS. Instead, ask KMS for a key, then encrypt the data locally. This is envelope encryption.

How Envelope Encryption Works β€” Step by Step Core
  1. GenerateDataKey
    Your app calls kms:GenerateDataKey with a CMK ID. KMS returns TWO things: a plaintext data key + an encrypted copy of that same key.
  2. Encrypt data locally
    Use the plaintext data key with AES-256 to encrypt your file/volume/database locally β€” no network call, no size limit, blazing fast.
  3. Discard plaintext key from memory
    Immediately delete the plaintext data key. It existed only for the duration of the encrypt operation. Zero it out.
  4. Store encrypted key alongside data
    Store the encrypted data key (the "envelope") with the ciphertext. It's safe β€” the encrypted key is useless without KMS.
  5. Decrypt: retrieve encrypted key β†’ call KMS
    To decrypt, read the encrypted data key, call kms:Decrypt to get the plaintext key back, then decrypt locally.
Diagram 4-1 Β· Envelope Encryption β€” Complete Flow
ENCRYPTION (Top) Β· DECRYPTION (Bottom) ENCRYPT PATH GenerateDataKey Call KMS API πŸ”‘ Plaintext Data Key πŸ” Encrypted Data Key Local AES Encrypt Fast, no size limit Data (GB/TB) πŸ“¦ Ciphertext πŸ” Enc Key (stored) ⚠️ Plaintext key discarded from memory immediately β€” β€” β€” DECRYPTION β€” β€” β€” DECRYPT PATH πŸ” Read Encrypted Key from stored envelope KMS Decrypt Returns plaintext key πŸ”‘ Plaintext Data Key Local AES Decrypt Returns original data βœ“ Plaintext Data Only 2 KMS API calls total (GenerateDataKey + Decrypt) β€” data never leaves your environment
Encrypt: 1 API call (GenerateDataKey) β†’ local encryption Β· Decrypt: 1 API call (Decrypt) β†’ local decryption
GenerateDataKey vs GenerateDataKeyWithoutPlaintext Core
APIReturns Plaintext?When to Use
GenerateDataKeyYes β€” plaintext + encrypted copyWhen you need to encrypt data immediately
GenerateDataKeyWithoutPlaintextNo β€” encrypted copy onlyWhen you'll encrypt later (pre-generate keys, store for future use)

GenerateDataKeyWithoutPlaintext is used when you want to prepare encrypted data keys in advance. For example, a key management system generates keys for future messages β€” the plaintext key is only recovered (via kms:Decrypt) when actually needed.

Key Point

Both APIs create the SAME data key. The difference is only whether KMS returns the plaintext immediately or keeps it hidden until you explicitly decrypt the encrypted copy later.

Why "Envelope" Encryption? Beginner
The Metaphor

Imagine putting a letter (your data) inside an envelope.

The envelope is sealed with a wax stamp (the data key).

The wax stamp itself is locked in a safe (encrypted by the CMK).

To read the letter: open the safe β†’ get the stamp β†’ open the envelope.

AWS Translation
  • Letter = your data (any size)
  • Envelope seal = data key (AES-256)
  • Safe = CMK in KMS HSM
  • Opening the safe = kms:Decrypt call
  • Only KMS can open that safe
Multi-Layer Envelope Encryption Deep

AWS services often use multiple layers of envelope encryption for performance and key management:

Layer 1: CMK
Customer Master Key in KMS HSM. Encrypts the bucket/volume key. Never leaves KMS.
Layer 2: Bucket Key
Intermediate key generated by KMS. Cached locally by the AWS service (e.g., S3). Reduces KMS API calls dramatically.
Layer 3: Object Key
Unique per-object data key. Generated locally using the bucket key. Each S3 object / EBS block gets its own key.
Diagram 4-2 Β· Multi-Layer Key Hierarchy (S3 Bucket Keys)
AWS KMS HSM Customer Master Key (CMK) encrypts ↓ S3 Bucket Key (Intermediate) Cached in S3 Β· Reduces KMS calls by 99% encrypts ↓ Object Key A Unique per object Object Key B Unique per object Object Key C Unique per object πŸ“„ Object A πŸ“„ Object B πŸ“„ Object C Compromise of one object key β†’ only that object exposed Β· CMK compromise β†’ everything exposed
CMK β†’ Bucket Key β†’ Object Keys β†’ Data Β· Each layer limits blast radius
S3 Bucket Keys β€” Cost Optimization Deep

S3 Bucket Keys are the most important optimization for SSE-KMS at scale:

AspectWithout Bucket KeyWith Bucket Key
KMS calls per object1 GenerateDataKey per PUT1 call per bucket key rotation (~few minutes)
Cost (1M objects/day)~$3/day in KMS charges~$0.01/day
CloudTrail events1 per object operation1 per bucket key generation
Throttling riskHigh at scaleVirtually eliminated
Encryption contextObject ARNBucket ARN (less granular)
Best Practice

Always enable S3 Bucket Keys for SSE-KMS buckets. It reduces KMS costs by up to 99% and eliminates throttling at scale. The only trade-off: CloudTrail shows the bucket ARN instead of individual object ARNs in KMS events.

Data Key Caching β€” Performance at Scale Deep

The AWS Encryption SDK supports data key caching β€” reusing a data key for multiple encrypt operations instead of calling GenerateDataKey every time.

⚑

Benefits

  • Reduces KMS API calls dramatically
  • Lower latency (no network round-trip)
  • Avoids KMS throttling
  • Reduces cost for high-throughput apps
⚠️

Trade-offs

  • Same key encrypts multiple messages
  • Larger blast radius if key compromised
  • Must set max age, max bytes, max messages
  • Not suitable for highest-security workloads
Max Age
Maximum time a cached key can be reused (e.g., 300 seconds). After this, a fresh GenerateDataKey call is made.
Max Messages
Maximum number of messages encrypted with one cached key (e.g., 1000). Limits blast radius.
Max Bytes
Maximum total bytes encrypted with one key (e.g., 10 GB). Prevents key wear-out for large messages.
When to Use
High-throughput apps (10,000+ ops/sec), microservices with many small messages, real-time data pipelines, IoT ingestion streams.
Implementation
Configure a Caching Cryptographic Materials Manager (Caching CMM) in the AWS Encryption SDK. It handles caching automatically β€” you only set the limits.
How AWS Services Use Envelope Encryption Core
ServiceData Key ScopeKey Hierarchy
S3 (SSE-KMS)Per object (or bucket key)CMK β†’ Bucket Key β†’ Object Key β†’ Object
EBSPer volumeCMK β†’ Volume Key β†’ Each I/O block
RDSPer instanceCMK β†’ Instance Key β†’ Tablespace files
DynamoDBPer tableCMK β†’ Table Key β†’ Per-item encryption
Lambda (env vars)Per function versionCMK β†’ Function Key β†’ Environment variables
Secrets ManagerPer secret versionCMK β†’ Data Key β†’ Secret value
EFSPer file systemCMK β†’ FS Key β†’ Per-file data key
Diagram 4-3 Β· EBS Volume Encryption β€” Envelope in Action
EC2 Instance Application writes data to EBS volume Nitro Card (Hardware) Holds plaintext volume key AES-XTS encryption Real-time encrypt/decrypt Zero performance impact encrypted EBS Volume All data encrypted at rest (AES-256) AWS KMS Decrypts volume key at boot only once at attach KMS called ONCE (volume attach) β†’ Nitro holds key in hardware β†’ encrypts every I/O at line speed
KMS decrypts volume key once at attach β†’ Nitro card handles all I/O encryption in hardware
Security Properties of Envelope Encryption Core
πŸ›‘οΈ

What Envelope Encryption Gives You

  • Separation of duties: admin of CMK β‰  user of data
  • Blast radius reduction: each object has unique key
  • Audit trail: every key usage logged in CloudTrail
  • Centralized revocation: disable CMK β†’ all data inaccessible
  • Performance: local encryption at hardware speed
πŸ”‘

Critical Insight

  • Deleting a CMK = permanent data loss
  • All data keys encrypted by that CMK become undecryptable
  • 7–30 day waiting period exists for this reason
  • No recovery possible β€” AWS cannot help
  • This is why key policies matter so much
🎯 Exam Tips β€” Envelope Encryption
  • "Encrypt large files with KMS" β†’ Envelope encryption. GenerateDataKey β†’ local AES encrypt.
  • "4 KB limit" β†’ Direct KMS Encrypt API limit. For anything larger β†’ envelope encryption.
  • "Reduce KMS costs for S3" β†’ Enable S3 Bucket Keys (reduces calls by 99%).
  • "KMS throttling" β†’ Use data key caching, S3 bucket keys, or request quota increase.
  • "How does EBS encryption work?" β†’ KMS decrypts volume key once at attach; Nitro card encrypts all I/O in hardware.
  • "What if CMK is deleted?" β†’ All data encrypted by data keys from that CMK is permanently lost.
  • "GenerateDataKeyWithoutPlaintext" β†’ Pre-generate encrypted keys for later use (message queuing, batch processing).
Chapter 04 Summary β€” Envelope Encryption
  • The pattern: GenerateDataKey β†’ encrypt locally β†’ discard plaintext key β†’ store encrypted key with data.
  • Why: KMS 4 KB limit + performance + cost. Real data never leaves your environment.
  • Two API calls total: GenerateDataKey (encrypt) + Decrypt (decrypt). That's it.
  • Multi-layer: CMK β†’ Bucket/Volume Key β†’ Object/Block Key β†’ Data. Each layer limits blast radius.
  • S3 Bucket Keys: Cache intermediate key, reduce KMS calls 99%, always enable for SSE-KMS.
  • Data Key Caching: AWS Encryption SDK feature. Reuse keys with max age/messages/bytes limits.
  • EBS: KMS decrypts volume key once β†’ Nitro card handles all I/O encryption in hardware.
  • CMK deletion = permanent data loss. 7–30 day waiting period is your safety net.
Chapter 04 β€” Key Takeaway

Envelope encryption is THE mechanism that makes KMS practical. KMS protects a small data key; that data key protects terabytes of data locally. Only 2 API calls needed regardless of data size. Deleting the CMK makes ALL data it protected permanently unrecoverable.

Chapter 04 of 08
05
Chapter Five
Key Policies & Permissions

KMS has its own authorization model that is different from standard IAM. Every KMS key has a key policy β€” a resource-based policy that is the primary access control mechanism. Without it, even the root account can be locked out.

Critical Difference

Unlike S3 or Lambda, a KMS key policy is mandatory. If no key policy explicitly grants access, IAM policies alone are insufficient. The key policy must either grant access directly OR enable IAM policies to grant access.

Key Policy β€” The Primary Gatekeeper Core

Every KMS key has exactly one key policy (up to 32 KB). It determines who can use and manage the key. The default key policy contains one critical statement:

The Default Key Policy Statement

  • Effect: Allow
  • Principal: arn:aws:iam::ACCOUNT-ID:root
  • Action: kms:*
  • Resource: * (this key)

This statement does NOT grant access to the root user directly. It enables IAM policies in the account to grant KMS permissions. Without this statement, IAM policies are ignored for this key.

Key Insight

The root principal statement is a delegation β€” it says "I trust this account's IAM system to manage access." Remove it, and ONLY explicit key policy statements control access. This is how keys get permanently locked.

The Three-Layer Access Model Core

Access to a KMS key is the union of three layers (all must align for access to be granted):

πŸ“œ

Layer 1: Key Policy

  • Resource-based policy on the key itself
  • Always evaluated (cannot be bypassed)
  • Must explicitly allow OR delegate to IAM
  • 32 KB maximum size
πŸ‘€

Layer 2: IAM Policies

  • Identity-based (attached to user/role)
  • Only works IF key policy enables IAM
  • Standard IAM Allow/Deny rules
  • Supports conditions, resource ARNs
🎫

Layer 3: Grants

  • Temporary, programmatic permissions
  • Created by key users for delegation
  • Used by AWS services internally
  • Can be revoked instantly
Diagram 5-1 Β· KMS Access Evaluation Logic
KMS API Request Key Policy Evaluation Does key policy ALLOW this principal? YES (direct) βœ“ ALLOWED delegates to IAM IAM Policy Evaluation Does IAM policy ALLOW kms:Action? YES βœ“ ALLOWED NO β†’ check grants Grant Evaluation Does an active grant cover this? YES βœ“ ALLOWED NO βœ— DENIED ⚠️ Explicit DENY anywhere β†’ always wins Key policy is ALWAYS checked first. If it doesn't allow OR delegate, access is denied regardless of IAM.
Key Policy β†’ IAM Policy β†’ Grants Β· Explicit Deny always wins at any layer
Common Key Policy Statements Core
Statement PurposePrincipalActionsWhy
Enable IAMarn:aws:iam::ACCT:rootkms:*Lets IAM policies manage access (default)
Key Administratorarn:aws:iam::ACCT:role/Adminkms:Create*, kms:Describe*, kms:Enable*, kms:List*, kms:Put*, kms:Update*, kms:Revoke*, kms:Disable*, kms:Delete*, kms:Tag*, kms:UntagResource, kms:ScheduleKeyDeletion, kms:CancelKeyDeletionManage key lifecycle (cannot use for crypto)
Key Userarn:aws:iam::ACCT:role/AppRolekms:Encrypt, kms:Decrypt, kms:ReEncrypt*, kms:GenerateDataKey*, kms:DescribeKeyUse key for cryptographic operations
Grant Delegationarn:aws:iam::ACCT:role/AppRolekms:CreateGrant, kms:ListGrants, kms:RevokeGrantAllow role to delegate access to AWS services
Cross-Accountarn:aws:iam::OTHER-ACCT:rootkms:Encrypt, kms:Decrypt, kms:GenerateDataKey*, kms:DescribeKeyAllow other account to use key (they also need IAM policy)
Separation of Duties β€” Admin vs User Deep

A critical security pattern: the person who manages a key should NOT be the person who uses it for encryption:

Key Administrator
  • Can enable/disable the key
  • Can modify key policy
  • Can schedule deletion
  • Can tag and describe
  • Cannot encrypt or decrypt
Key User
  • Can encrypt and decrypt
  • Can generate data keys
  • Can create grants for services
  • Cannot modify key policy
  • Cannot delete the key
Production Pattern

In regulated environments, ensure no single principal has both kms:PutKeyPolicy and kms:Decrypt. This prevents a compromised admin from both accessing data and covering their tracks.

Cross-Account Key Access Deep

Sharing a KMS key across accounts requires both sides to grant permission:

  1. Key policy in Account A (key owner)
    Add a statement allowing arn:aws:iam::ACCOUNT-B:root to use the key (kms:Encrypt, kms:Decrypt, kms:GenerateDataKey*, kms:DescribeKey).
  2. IAM policy in Account B (key user)
    Attach an IAM policy to the role/user in Account B allowing the same KMS actions on the key ARN in Account A.
  3. Both must align
    Missing either side = access denied. This is the same dual-authorization model as S3 cross-account access.
Alternative: Grants

Instead of modifying the key policy, Account A can create a grant for a specific principal in Account B. Grants are more temporary and don't require key policy changes β€” useful for automated cross-account workflows.

Grants β€” Temporary Programmatic Access Deep

Grants provide temporary, scoped access to a KMS key without modifying the key policy. AWS services use grants internally when you select "encrypt with CMK":

Grantee Principal
The IAM principal receiving permissions (e.g., an EBS service role or a Lambda execution role).
Operations
Specific KMS actions allowed: Encrypt, Decrypt, GenerateDataKey, ReEncryptFrom, ReEncryptTo, CreateGrant, RetireGrant, DescribeKey.
Constraints
Optional encryption context constraints β€” grant only valid when specific context key-value pairs are present.
Retiring Principal
The principal allowed to retire (delete) the grant. Usually the service that created it.

When AWS Uses Grants

  • EBS creating an encrypted volume
  • RDS encrypting a database instance
  • Lambda decrypting environment variables
  • Secrets Manager accessing secrets
  • Any service needing temporary key access

Grant Lifecycle

  • CreateGrant β€” issue new grant
  • Grant token β€” use immediately (before replication)
  • ListGrants β€” view active grants
  • RetireGrant β€” grantee removes own grant
  • RevokeGrant β€” admin revokes any grant
Diagram 5-2 Β· KMS VPC Endpoint β€” Network-Level Access Control
VPC Private Subnet Application (EC2) kms:Decrypt call KMS VPC Endpoint Interface endpoint (PrivateLink) + Endpoint Policy private AWS KMS Regional service HSM fleet PrivateLink Endpoint Policy can restrict: actions, principals, key ARNs Traffic never traverses the public internet β€” stays within AWS network
VPC Endpoint + Endpoint Policy = network-level restriction on KMS access (no internet gateway needed)
KMS Condition Keys β€” Fine-Grained Control Deep

KMS supports powerful condition keys for both key policies and IAM policies:

Condition KeyControlsExample Use
kms:ViaServiceWhich AWS service is making the callAllow only S3 to use this key
kms:CallerAccountAWS account of the callerRestrict cross-account usage
kms:EncryptionContext:keyRequire specific encryption contextOnly decrypt if context matches
kms:GrantIsForAWSResourceGrant must be for AWS service usePrevent grants to arbitrary principals
kms:KeyOriginWhere key material came fromOnly allow KMS-generated keys
kms:KeySpecKey algorithm specificationOnly allow symmetric keys
kms:RequestAliasAlias used in requestABAC β€” control by alias name pattern
aws:SourceVpceVPC endpoint IDOnly allow from specific VPC endpoint
Powerful Pattern: kms:ViaService

Use kms:ViaService to ensure a key can only be used through specific AWS services. Example: allow the key for S3 encryption but prevent direct kms:Encrypt calls. This prevents data exfiltration through direct KMS API usage.

Dangerous Anti-Patterns β€” How Keys Get Locked Pro
πŸ’€

Lockout Scenario 1

  • Remove root account from key policy
  • Remove all admins from key policy
  • Now NO ONE can modify the key policy
  • Key becomes permanently unusable
  • Fix: Contact AWS Support (they can reset)
πŸ”’

Lockout Scenario 2

  • Key policy grants access to a specific role
  • That role is deleted from IAM
  • No other principal in key policy
  • Root statement was removed
  • Fix: AWS Support only (cannot self-recover)
Prevention Rule

Never remove the root account statement from a key policy unless you have a deliberate reason and another explicit principal that can manage the key. Always test key policy changes in a non-production key first.

Diagram 5-3 Β· Cross-Account KMS Access β€” Dual Authorization
ACCOUNT A (Key Owner) KMS Key CMK in Account A Key Policy: Principal: arn:aws:iam::ACCT-B:root Actions: kms:Decrypt, kms:DescribeKey βœ“ Step 1 complete ACCOUNT B (Key User) IAM Role App role in Account B IAM Policy: Resource: arn:aws:kms:us-east-1:ACCT-A:key/xxx Actions: kms:Decrypt, kms:DescribeKey βœ“ Step 2 complete BOTH required
Cross-account = Key Policy (owner) + IAM Policy (user). Missing either = Access Denied.
🎯 Exam Tips β€” Key Policies & Permissions
  • "IAM policy alone doesn't work for KMS" β†’ Key policy must enable IAM OR directly allow the principal.
  • "Cross-account KMS" β†’ Need BOTH: key policy in owner account + IAM policy in user account.
  • "Restrict key to S3 only" β†’ Use condition kms:ViaService: s3.*.amazonaws.com.
  • "Key is locked, no one can access" β†’ Contact AWS Support. They can reset the key policy (only for account root).
  • "Temporary access to KMS key" β†’ Use Grants. No key policy change needed.
  • "Who can delete vs who can encrypt" β†’ Separation of duties. Key admin β‰  Key user.
  • "Prevent direct KMS API calls" β†’ Use kms:ViaService condition + VPC endpoint policy.
  • "ABAC for KMS" β†’ Use kms:RequestAlias or resource tags with aws:ResourceTag conditions.
Chapter 05 Summary β€” Key Policies & Permissions
  • Key policy is mandatory: Unlike other AWS services, IAM alone cannot grant KMS access. Key policy must allow or delegate.
  • Default root statement: Enables IAM policies. Remove it β†’ only explicit key policy principals can access.
  • Three layers: Key Policy + IAM Policies + Grants. Access = union of all three (minus explicit denies).
  • Separation of duties: Key admins (manage lifecycle) vs Key users (encrypt/decrypt). Never combine in production.
  • Cross-account: Key policy (owner) + IAM policy (user). Both required.
  • Grants: Temporary programmatic access. AWS services use them internally. Can be revoked instantly.
  • Condition keys: kms:ViaService, kms:EncryptionContext, kms:CallerAccount for fine-grained control.
  • Lockout prevention: Never remove root statement without another admin. AWS Support is last resort.
Chapter 05 β€” Key Takeaway

KMS access requires the key policy to say "yes" first. Without a key policy statement (direct or delegated), IAM policies are powerless. Cross-account needs both sides. Grants provide temporary access without policy changes. One wrong key policy edit can permanently lock a key.

Troubleshooting β€” Common KMS Errors Deep
ErrorSymptomCommon CauseFix
AccessDeniedException"User is not authorized to perform kms:Decrypt"Key policy missing IAM delegation OR IAM policy missing kms: actionAdd root account to key policy + kms:Decrypt to IAM policy
ValidationException"Ciphertext is larger than 4096 bytes"Direct Encrypt API called with >4 KB dataUse GenerateDataKey + local AES encryption (envelope encryption)
ThrottlingException"Rate exceeded" / "Request was throttled"Exceeded regional KMS quotaS3 Bucket Keys, data key caching, request quota increase
NotFoundException"Key ARN does not exist"Wrong region, deleted key, or typo in ARNVerify region (keys are regional). Check key state. Use correct ARN format.
InvalidKeyUsageException"Operation not supported for this key usage"Asymmetric key used for symmetric op (or vice versa)Check KeySpec. Create separate keys for different purposes.
DependencyTimeoutException"Custom key store is unavailable"CloudHSM cluster unreachableCheck CloudHSM health. Ensure kmsuser logged in. Verify VPC connectivity.
KMSInvalidStateException"Key is pending deletion/disabled"Key was disabled or scheduled for deletionEnableKey or CancelKeyDeletion if within waiting period
Debugging Tip

For AccessDenied: check three things in order β€” (1) Key Policy allows principal or delegates to IAM, (2) IAM policy includes kms: actions on the key ARN, (3) No explicit Deny in any SCP, boundary, or policy. Use IAM Policy Simulator and CloudTrail to pinpoint the failure.

Chapter 05 of 08
06
Chapter Six
Service Integration

KMS integrates with 100+ AWS services. Understanding how each service uses KMS β€” what encryption options exist, what permissions are needed, and what CloudTrail events are generated β€” is essential for both architecture and security.

S3 β€” Server-Side Encryption Options Core
OptionKey ManagementWho Manages KeyCostAudit (CloudTrail)
SSE-S3AES-256, S3-managedAWS (invisible)FreeNo KMS events
SSE-KMSKMS CMKYou (key policy)$1/mo + API callsFull audit trail
SSE-KMS + Bucket KeyKMS CMK + cached keyYou (key policy)$1/mo + minimal APIReduced granularity
SSE-CCustomer-provided keyYou (full lifecycle)FreeNo KMS events
DSSE-KMSDual-layer KMS encryptionYou (key policy)$1/mo + API callsFull audit trail
πŸ†

When to Choose SSE-KMS

  • Need audit trail of every access
  • Need to control who can decrypt
  • Regulatory/compliance requirement
  • Cross-account data sharing with control
  • Need to revoke access centrally
πŸ“‹

S3 + KMS Permissions Needed

  • kms:GenerateDataKey β€” for PutObject
  • kms:Decrypt β€” for GetObject
  • kms:DescribeKey β€” key validation
  • Key policy OR IAM + grant must allow
  • Bucket policy alone is NOT enough
Common Mistake

Granting s3:GetObject without kms:Decrypt results in Access Denied for SSE-KMS objects. The principal needs BOTH S3 permissions AND KMS permissions on the specific key.

EBS β€” Volume & Snapshot Encryption Core
Default Encryption
Enable at account/region level. All new EBS volumes automatically encrypted with a default CMK (aws/ebs or custom).
Volume Key
Each volume gets a unique data key (AES-256-XTS). Decrypted once at attach time; held in Nitro card memory.
Snapshot Encryption
Snapshots of encrypted volumes are encrypted with the same key. Copy to another region β†’ must specify key in target region.
Cross-Account Sharing
Share encrypted snapshot β†’ recipient must have access to the KMS key (or re-encrypt with their own key during copy).
Encrypt Existing Volume
Cannot encrypt in-place. Create snapshot β†’ copy snapshot with encryption β†’ create new volume from encrypted snapshot.
EBS + KMS Permission Chain

EC2 instance needs: IAM role with kms:CreateGrant + kms:Decrypt + kms:DescribeKey + kms:GenerateDataKeyWithoutPlaintext. EBS internally creates a grant to decrypt the volume key at attach time.

RDS & Aurora β€” Database Encryption Core
πŸ—„οΈ

What's Encrypted

  • DB storage (data files)
  • Automated backups
  • Read replicas
  • Snapshots
  • Logs (if enabled)
⚠️

Limitations

  • Cannot encrypt existing unencrypted DB
  • Must snapshot β†’ copy with encryption β†’ restore
  • Read replica must use same or different CMK (same region = same; cross-region = different)
  • Cannot change CMK after creation
DynamoDB β€” Encryption at Rest Core
OptionKeyCostRotationControl
AWS Owned (default)AWS-managed, invisibleFreeAutomatic (varies)None
AWS Managed (aws/dynamodb)Visible in KMS consoleFreeYearly (automatic)View only
Customer ManagedYour CMK$1/mo + usageConfigurableFull (policy, disable, delete)

Key point: DynamoDB encryption is always on β€” you only choose which key type. Client-side encryption (using the DynamoDB Encryption Client) adds field-level encryption on top.

Lambda, Secrets Manager & SSM Parameter Store Core
Ξ»

Lambda

  • Environment variables encrypted at rest
  • Default: AWS managed key (aws/lambda)
  • Optional: CMK for additional control
  • Helpers for decrypt in function code
  • Grant created at deploy time
πŸ”’

Secrets Manager

  • Each secret version encrypted with data key
  • Default: aws/secretsmanager key
  • CMK for cross-account secret sharing
  • Automatic rotation built-in
  • kms:Decrypt needed to retrieve secret
βš™οΈ

SSM Parameter Store

  • SecureString type uses KMS
  • Standard: aws/ssm default key
  • Advanced: custom CMK
  • kms:Decrypt on the key required
  • Free tier: 10,000 standard params
Diagram 6-1 Β· AWS Services KMS Integration Map
AWS KMS Central Key Management 100+ integrations STORAGE S3 EBS EFS Glacier DATABASE RDS / Aurora DynamoDB Redshift ElastiCache COMPUTE Lambda ECS / Fargate SageMaker SECURITY Secrets Manager SSM Params ACM SQS SNS
KMS is the central hub β€” every service uses envelope encryption with grants for temporary key access
CloudTrail β€” Auditing KMS Usage Deep

Every KMS API call is logged in CloudTrail. This provides a complete audit trail of who accessed which key, when, and from which service:

Event FieldWhat It ShowsExample Value
eventNameKMS API actionDecrypt, GenerateDataKey
userIdentityWho made the callRole ARN, assumed-role session
requestParameters.keyIdWhich key was usedKey ARN or alias
requestParameters.encryptionContextContext key-value pairsaws:s3:arn, aws:ebs:id
sourceIPAddressCaller originIP or service name (e.g., s3.amazonaws.com)
vpcEndpointIdVPC endpoint usedvpce-0abc123...
Security Monitoring

Set up CloudWatch alarms for: unusual Decrypt volume, key policy changes (PutKeyPolicy), DisableKey, ScheduleKeyDeletion, and failed access attempts. These are early indicators of compromise or misconfiguration.

Messaging β€” SQS, SNS & Kinesis Core

SQS + KMS

  • Server-side encryption (SSE-KMS)
  • Messages encrypted at rest
  • Producer needs kms:GenerateDataKey
  • Consumer needs kms:Decrypt
  • Data key cached for reuse period

SNS + KMS

  • Topic encryption with CMK
  • Publisher needs kms:GenerateDataKey
  • Subscribers (SQS, Lambda) need kms:Decrypt
  • Cross-account: key policy must allow subscriber
  • HTTPS endpoints receive decrypted

Kinesis + KMS

  • Stream-level encryption
  • Each shard gets data keys
  • Producer: kms:GenerateDataKey
  • Consumer: kms:Decrypt
  • High throughput = watch KMS quotas
Diagram 6-2 Β· S3 SSE-KMS β€” PutObject & GetObject Flow
PutObject (UPLOAD) Client PutObject + data Amazon S3 Needs data key GenerateDataKey AWS KMS Returns plain + enc key Encrypted Object + encrypted data key GetObject (DOWNLOAD) Client GetObject request Amazon S3 Has enc data key Decrypt (key) AWS KMS Returns plaintext key Decrypted Data Returned to client Required Permissions (Caller's IAM Role) PUT: s3:PutObject + kms:GenerateDataKey Β· GET: s3:GetObject + kms:Decrypt Missing KMS permission β†’ AccessDenied (even if S3 permission exists)
PUT: S3 calls GenerateDataKey β†’ encrypts β†’ stores Β· GET: S3 calls Decrypt β†’ decrypts β†’ returns plaintext
KMS Request Quotas & Throttling Deep
Operation TypeDefault Quota (per second)Increasable?Applies To
Cryptographic operations (symmetric)5,500 – 30,000 (varies by region)Yes (via Support)Encrypt, Decrypt, GenerateDataKey, ReEncrypt
Cryptographic operations (asymmetric RSA)500YesRSA Sign, Encrypt, Decrypt
Cryptographic operations (asymmetric ECC)300YesECC Sign
Management operations5 – 50NoCreateKey, PutKeyPolicy, ScheduleKeyDeletion

What happens when exceeded: KMS returns ThrottlingException. AWS SDKs automatically implement exponential backoff with jitter. Set CloudWatch alarm on ThrottledRequests metric at >100/minute.

πŸ›‘οΈ Throttling Mitigation

  • Enable S3 Bucket Keys (biggest impact)
  • Use data key caching (Encryption SDK)
  • Request quota increase via Support
  • Distribute across multiple CMKs
  • Use exponential backoff + jitter

πŸ“Š Monitoring

  • CloudWatch: ThrottledRequests metric
  • CloudWatch: SecondsUntilKeyMaterialExpiration
  • AWS Trusted Advisor: KMS quota check
  • Service Quotas dashboard
  • Set alarms at 80% utilization
Diagram 6-3 Β· Cross-Account Encrypted Snapshot Sharing
ACCOUNT A (Source) EBS Volume Encrypted (Key A) Snapshot Share β†’ Account B CMK-A (Key Policy) Must allow Account B 1. Share snapshot 2. Grant Key A access to Account B ACCOUNT B (Destination) Copy Snapshot Re-encrypt β†’ Key B CMK-B (Own Key) Full control here New Vol Key B 3. Copy with own CMK 4. Create volume from copy
Source shares snapshot + grants key access Β· Destination copies with own key for independence
🎯 Exam Tips β€” Service Integration
  • "AccessDenied on S3 GetObject" β†’ Check if object is SSE-KMS encrypted. Principal needs kms:Decrypt on that key.
  • "Share encrypted EBS snapshot cross-account" β†’ Share snapshot + grant key access OR copy with recipient's own key.
  • "Encrypt existing unencrypted RDS" β†’ Snapshot β†’ Copy with encryption β†’ Restore from encrypted snapshot.
  • "Reduce KMS costs for S3 at scale" β†’ Enable S3 Bucket Keys.
  • "KMS ThrottlingException" β†’ Data key caching, bucket keys, or request quota increase.
  • "DynamoDB encryption" β†’ Always encrypted. Choose between AWS owned (free, no control), AWS managed, or CMK.
  • "Lambda env var encryption" β†’ Default uses aws/lambda. Use CMK for cross-account or policy control.
  • "SQS cross-account with CMK" β†’ Key policy must allow producing account's role to call kms:GenerateDataKey.
Chapter 06 Summary β€” Service Integration
  • S3 SSE-KMS: GenerateDataKey on PUT, Decrypt on GET. Use Bucket Keys for cost. Missing kms: permission = AccessDenied.
  • EBS: Volume key decrypted once at attach (Nitro card). Cannot encrypt in-place. Snapshot sharing needs key access.
  • RDS/Aurora: Encryption at creation only. Snapshot β†’ copy encrypted β†’ restore for existing DBs.
  • DynamoDB: Always encrypted. Three key options: AWS owned, AWS managed, Customer managed.
  • Lambda/Secrets/SSM: Env vars, secrets, SecureStrings all use envelope encryption via KMS.
  • SQS/SNS/Kinesis: Message encryption at rest. Producer needs GenerateDataKey, consumer needs Decrypt.
  • CloudTrail: Every KMS API call logged. Monitor for unusual patterns, policy changes, deletions.
  • Quotas: 5,500–30,000 req/sec symmetric. Mitigate with caching, bucket keys, quota increases.
KMS Cost Optimization β€” Production Guide Deep
ComponentCostNotes
Customer Managed Key (CMK)$1/month per keyCharged even when not in use
AWS Managed Key$0 (free)No monthly fee, only API charges
API calls (Encrypt, Decrypt, GenerateDataKey)$0.03 per 10,000 requestsBiggest cost driver at scale
S3 Bucket Keys$0Free feature that reduces API costs 99%

Typical monthly costs by workload:

WorkloadWithout OptimizationWith OptimizationStrategy
S3 bucket (1M objects/day, SSE-KMS)~$90/month~$1/monthEnable Bucket Keys
100 EBS volumes + daily snapshots~$104/month~$100/monthConsolidate CMKs
Lambda (10M invocations, env vars encrypted)~$30/month~$30/monthUse AWS managed key if no cross-account need
High-throughput messaging (100K msg/sec)~$26K/month~$50/monthData key caching + reuse period
Cost Warning

Deleting a CMK removes the $1/month fee but makes all data encrypted with it permanently unrecoverable. Never delete a CMK without confirming full data migration or intentional erasure.

Chapter 06 β€” Key Takeaway

Every AWS encryption integration follows the same pattern: service calls GenerateDataKey or Decrypt on your behalf using grants. You need both service permissions AND KMS permissions. Missing either = AccessDenied. S3 Bucket Keys and data key caching solve scale/cost problems.

Chapter 06 of 08
07
Chapter Seven
Advanced Topics

Beyond standard KMS usage, AWS offers advanced key management options for organizations with strict compliance, data sovereignty, or hybrid-cloud requirements. These options trade convenience for greater control.

Custom Key Stores β€” CloudHSM-Backed Keys Deep

A Custom Key Store connects KMS to your own AWS CloudHSM cluster. Key material is generated and stored in HSMs you control β€” not in the shared KMS HSM fleet.

πŸ›οΈ

When to Use Custom Key Store

  • Regulatory requirement for single-tenant HSM
  • Need FIPS 140-2 Level 3 (KMS default is Level 2)
  • Must have direct control over HSM hardware
  • Compliance mandates key isolation
  • Organization requires explicit HSM audit logs
⚠️

Trade-offs

  • CloudHSM cluster cost (~$1.50/hr per HSM)
  • You manage HSM availability (min 2 HSMs)
  • Lower performance than standard KMS
  • More complex setup and maintenance
  • Key operations fail if HSM cluster is down
  1. Create CloudHSM Cluster
    Deploy at least 2 HSMs across AZs for high availability. Initialize the cluster and set crypto officer credentials.
  2. Create Custom Key Store in KMS
    Link KMS to your CloudHSM cluster. KMS authenticates as a crypto user (kmsuser) on the HSMs.
  3. Create CMKs in Custom Key Store
    Keys created here have Origin: AWS_CLOUDHSM. Key material lives exclusively in your HSM cluster.
  4. Use like any other CMK
    All KMS APIs work the same. AWS services integrate seamlessly. The difference is where key material lives.
External Key Stores (XKS) β€” Keys Outside AWS Pro

XKS (launched 2022) lets you store and use key material in an HSM entirely outside of AWS β€” in your own data center or another cloud. KMS proxies requests to your external key manager.

XKS Proxy
A software component you deploy. Translates KMS API calls into requests to your external key manager (Thales, Entrust, Fortanix, etc.).
Key Material
Never enters AWS. KMS sends encrypted data to the proxy, proxy decrypts locally, returns result. AWS never sees plaintext key.
Data Sovereignty
Meet regulations requiring keys to remain in specific jurisdictions. Perfect for EU data residency, government, and financial services.
Kill Switch
Disconnect the XKS proxy β†’ all decryption instantly stops. Ultimate control over AWS access to your data. Revocation is immediate.
XKS Limitations

External key stores have higher latency, lower throughput, and introduce a dependency on external infrastructure. If your key manager goes offline, AWS services using those keys will fail. This is by design β€” it gives you the "kill switch."

Diagram 7-1 Β· Key Store Options β€” Where Does Key Material Live?
Standard KMS Key in AWS shared HSM fleet FIPS 140-2 Level 2 βœ“ Highest performance βœ“ Lowest cost ($1/key/mo) 99% of workloads Custom Key Store Key in YOUR CloudHSM cluster FIPS 140-2 Level 3 βœ“ Single-tenant HSM βœ“ Direct HSM audit ~$1.50/hr per HSM External Key Store (XKS) Key OUTSIDE AWS entirely Your HSM / Key Manager βœ“ Data sovereignty βœ“ Kill switch Highest latency Least Control Most Convenient Most Control Most Complex Balanced ← AWS manages infrastructure Β· Β· Β· You manage infrastructure β†’ All three work with same KMS APIs and AWS service integrations
Standard (99% of cases) β†’ Custom Key Store (compliance) β†’ XKS (sovereignty/kill switch)
Imported Key Material (Bring Your Own Key) Deep

You can import your own symmetric key material into a KMS key instead of letting KMS generate it. This gives you control over key generation but adds significant operational burden.

  1. Create CMK with no key material
    Specify Origin: EXTERNAL. KMS creates the key metadata and policy but leaves the key material empty.
  2. Download wrapping key & import token
    KMS provides an RSA public key (wrapping key) and an import token. These expire in 24 hours.
  3. Encrypt your key material
    Wrap your 256-bit symmetric key with the RSA wrapping key using RSAES_OAEP_SHA_256.
  4. Import into KMS
    Upload the wrapped key + import token. Optionally set an expiration date (key auto-deletes material when expired).

BYOK Use Cases

  • Prove key generated in specific HSM
  • Set key expiration (material auto-deletes)
  • Comply with "key generated on-premises" rules
  • Same key material across multiple regions
  • Maintain key escrow outside AWS

BYOK Limitations

  • No automatic key rotation
  • Cannot use with Custom Key Store
  • You're responsible for key material backup
  • Delete material β†’ must re-import (if you still have it)
  • Only symmetric + HMAC keys supported
Multi-Region Keys β€” Encrypt Anywhere, Decrypt Anywhere Deep

Multi-Region keys share the same key material across multiple AWS regions. They look like independent keys but can decrypt each other's ciphertext.

Primary Key
The original key created in one region. Can replicate to other regions. Key material originates here.
Replica Key
A copy in another region with the same key material and same Key ID (different ARN). Can be promoted to primary.
Use Case: DR
Encrypt data in us-east-1, replicate to eu-west-1. Decrypt in eu-west-1 without cross-region KMS calls.
Use Case: Global Tables
DynamoDB Global Tables with client-side encryption need same key in every replica region.
Key ID Prefix

Multi-Region keys have a key ID starting with mrk- (e.g., mrk-1234abcd...). This prefix is how you identify them. Standard keys start with a random UUID.

What Replicates

  • Key material (cryptographic bytes)
  • Key ID (same mrk- ID in all regions)
  • Automatic rotation setting
  • Key spec and key usage

What Does NOT Replicate

  • Key policy (independent per region)
  • Tags (set separately per region)
  • Aliases (create in each region)
  • Grants (region-specific)
Multi-Region Limitations

Max ~13 regions per MRK (soft limit). Deleting primary does NOT delete replicas (they become independent). Not supported for asymmetric keys or imported key material. Cannot change key material after initial replication.

Key Rotation β€” Deep Mechanics Deep
Key TypeRotationPeriodBehavior
AWS ManagedAutomatic (mandatory)Every year (365 days)Cannot disable or change period
Customer Managed (KMS material)Optional (configurable)90–2560 daysYou choose period, can disable
Customer Managed (imported)Manual onlyβ€”Must create new key + re-import
Asymmetric keysManual onlyβ€”Create new key + distribute public key
HMAC keysManual onlyβ€”Create new key + update applications
Custom Key StoreManual onlyβ€”Rotation not supported automatically
How Rotation Actually Works

When a key rotates, KMS generates new backing material but keeps the same Key ID and ARN. New encryptions use the new material. Old ciphertext is still decryptable because KMS retains all previous backing materials indefinitely. Your code never changes.

Diagram 7-2 Β· Multi-Region Keys β€” Replicate & Decrypt Across Regions
us-east-1 mrk-abc123 PRIMARY App β†’ Encrypt Data encrypted here Ciphertext replicated β†’ eu-west-1 mrk-abc123 REPLICA App β†’ Decrypt Local KMS call (fast) Same key material Data replicated (S3 CRR, DDB Global) Same Key ID in both regions Β· No cross-region KMS calls needed Β· Local decrypt = lower latency
Primary replicates key material to replicas Β· Data encrypted in one region decryptable in another β€” no cross-region calls
IAM Roles Anywhere β€” On-Premises KMS Access Pro

IAM Roles Anywhere lets on-premises workloads obtain temporary AWS credentials using X.509 certificates. Combined with KMS, this enables:

Pattern: Hybrid Encryption

  • On-prem server has X.509 cert from private CA
  • Authenticates via IAM Roles Anywhere
  • Gets temporary AWS credentials
  • Calls kms:Decrypt / kms:GenerateDataKey
  • Encrypts/decrypts data locally

Benefits

  • No long-term credentials stored on-prem
  • Full CloudTrail audit of on-prem KMS usage
  • Same key policies control on-prem + cloud
  • Rotate certificates (not static keys)
  • Revoke access by revoking cert trust
Nitro Enclaves β€” Isolated Processing with KMS Pro

Nitro Enclaves create isolated virtual machines with no persistent storage, no network, and no operator access. KMS can be configured to only release keys to a specific enclave:

Attestation
The enclave produces a cryptographic attestation document proving its identity (image hash, PCR values). KMS validates this before releasing keys.
Condition Key
Key policy uses kms:RecipientAttestation:ImageSha384 condition to restrict decrypt to a specific enclave image.
Use Case
Process PII, medical data, or financial records where even the EC2 instance owner (admin) should not see plaintext data.
Diagram 7-3 Β· BYOK Import Flow β€” Bring Your Own Key to KMS
ON-PREMISES HSM Generate 256-bit key Wrap with RSA pub key (from KMS) Upload wrapped key + import token AWS KMS Unwrap in HSM RSA private key (KMS internal) CMK Ready Origin: EXTERNAL Optional expiration date Use normally Same APIs, same service integrations as KMS keys You control key generation Β· Set expiration Β· Re-import if needed Β· No automatic rotation
Generate key on-prem β†’ Wrap with KMS public key β†’ Upload β†’ Use as normal CMK (no auto-rotation)
🎯 Exam Tips β€” Advanced Topics
  • "FIPS 140-2 Level 3" β†’ Custom Key Store (CloudHSM). Standard KMS is Level 2.
  • "Keys must not reside in AWS" β†’ External Key Store (XKS).
  • "Kill switch to revoke all AWS access" β†’ XKS β€” disconnect the proxy.
  • "Same key material in multiple regions" β†’ Multi-Region keys (mrk- prefix).
  • "Key rotation for imported keys" β†’ Manual only. Create new key, import new material, update alias.
  • "DR for encrypted data" β†’ Multi-Region keys OR replicate + re-encrypt in target region.
  • "On-premises workload needs KMS" β†’ IAM Roles Anywhere + KMS API calls.
  • "Process sensitive data, even admin can't see" β†’ Nitro Enclaves with KMS attestation condition.
  • "Key has expiration date" β†’ Imported key material with expiration set.
Chapter 07 Summary β€” Advanced Topics
  • Custom Key Store: CloudHSM-backed. FIPS 140-2 Level 3. Single-tenant. ~$1.50/hr per HSM. You manage availability.
  • External Key Store (XKS): Key material outside AWS entirely. Kill switch capability. Highest latency. Data sovereignty.
  • BYOK (Imported): Generate key on-prem β†’ wrap β†’ upload. No auto-rotation. Optional expiration. You maintain backup.
  • Multi-Region keys: Same key material replicated across regions. mrk- prefix. Encrypt in one region, decrypt in another.
  • Auto-Rotation: New backing material, same Key ID. Old ciphertext still decryptable. 90–2560 day configurable period.
  • IAM Roles Anywhere: On-prem β†’ X.509 cert β†’ temporary AWS creds β†’ KMS access. No long-term keys.
  • Nitro Enclaves: KMS releases keys only to attested enclave images. Even instance admin cannot see plaintext.
Chapter 07 β€” Key Takeaway

Standard KMS β†’ Custom Key Store β†’ External Key Store is a spectrum from most convenient to most control. Multi-Region keys solve DR/global apps. BYOK gives generation control. Choose based on compliance requirements β€” 99% of workloads should use standard KMS.

Chapter 07 of 08
08
Chapter Eight
Architecture Patterns

This final chapter ties everything together with real-world architecture patterns that combine KMS concepts into production-ready solutions. These are the patterns that appear in architecture reviews, certification exams, and enterprise deployments.

Pattern 1 β€” Multi-Account Encryption Strategy Pro

Enterprise organizations with multiple AWS accounts need a centralized encryption strategy. The recommended approach:

🏒

Centralized Key Account

  • Dedicated "Security/Keys" account
  • All CMKs created and managed here
  • Key administrators in this account only
  • Cross-account key policies grant usage
  • Centralized audit via CloudTrail
πŸ“‘

Workload Accounts

  • IAM roles with kms:Encrypt/Decrypt
  • Reference keys by alias ARN or key ARN
  • Cannot modify key policies
  • Cannot delete keys
  • Separation: data owners β‰  key owners
Why This Works

Centralized management means one team controls encryption policy. Even if a workload account is compromised, the attacker cannot modify key policies or delete keys. Revoking access = update one key policy statement.

Pattern 2 β€” Encrypted Data Lake with Access Control Deep

A data lake encryption pattern that uses different CMKs per data classification:

ClassificationS3 PrefixKMS KeyAccess
Publics3://lake/public/SSE-S3 (no KMS)Anyone with bucket access
Internals3://lake/internal/CMK: internal-data-keyAll data team roles
Confidentials3://lake/confidential/CMK: confidential-keyRestricted analysts only
Restricted/PIIs3://lake/restricted/CMK: pii-keyDPO + specific approved roles

Key insight: Even if someone has s3:GetObject on the entire bucket, they cannot read restricted data without kms:Decrypt permission on the PII key. KMS becomes your secondary access control layer.

Pattern 3 β€” Cross-Region Disaster Recovery Deep
  1. Create Multi-Region KMS key
    Primary in us-east-1, replica in us-west-2. Same key material in both regions.
  2. Encrypt data in primary region
    S3 objects, EBS snapshots, RDS automated backups β€” all encrypted with the multi-region key.
  3. Replicate to DR region
    S3 Cross-Region Replication, EBS snapshot copy, RDS cross-region read replica.
  4. Failover β€” decrypt immediately
    Data is decryptable immediately in DR region using the local replica key. No re-encryption needed. No cross-region KMS calls.
  5. Promote replica if primary fails
    If primary region is permanently lost, promote the replica to primary. Full control maintained in DR region.
Pattern 4 β€” Zero-Trust Encryption Architecture Pro

Defense-in-depth using KMS condition keys to build a zero-trust encryption layer:

πŸ”

Layer Stack

  • Network: VPC endpoint policy restricts KMS access to specific VPC
  • Identity: IAM policy with kms: actions + resource ARN
  • Resource: Key policy with kms:ViaService condition
  • Context: Encryption context must match expected values
  • Time: Grants with expiration for temporary access
βœ“

Result

  • Compromise of IAM alone β†’ insufficient
  • Compromise of S3 alone β†’ can't decrypt
  • Must satisfy ALL layers simultaneously
  • Full audit trail in CloudTrail
  • Instant revocation at any layer
Diagram 8-1 Β· Enterprise Multi-Account KMS Architecture
SECURITY ACCOUNT (Central) CMK: Prod CMK: Dev CMK: PII Key Admins: SecurityTeam role only PROD ACCOUNT App Role: kms:Encrypt, Decrypt S3, EBS, RDS (SSE-KMS) Cannot: PutKeyPolicy, DeleteKey DEV ACCOUNT App Role: kms:Encrypt, Decrypt Only dev-key access No access to prod or PII keys ANALYTICS ACCOUNT Analyst: kms:Decrypt only Read from prod S3 data lake No Encrypt (read-only access) key policy grants key policy grants One team manages keys (Security) Β· Workload accounts have minimal permissions Β· Revoke by updating one key policy
Security account owns all keys Β· Workload accounts get scoped permissions Β· No workload can modify or delete keys
Pattern 5 β€” Secure CI/CD Pipeline Secrets Deep
  1. Store secrets in Secrets Manager (CMK-encrypted)
    Database passwords, API keys, certificates stored encrypted with a dedicated CI/CD CMK.
  2. Pipeline role gets temporary access via grant
    CodePipeline/CodeBuild assume role with kms:Decrypt permission. Grant auto-retires after pipeline completes.
  3. Encryption context ties secret to pipeline
    Key policy requires encryption context: {"pipeline": "prod-deploy", "stage": "build"}. Wrong context = denied.
  4. CloudTrail captures every access
    Full audit: who accessed which secret, when, from which pipeline. Alert on unexpected access patterns.
Pattern 6 β€” Client-Side Encryption (AWS Encryption SDK) Deep
Server-Side (SSE)
  • AWS service encrypts after receiving data
  • Data in transit is plaintext (HTTPS protected)
  • AWS handles key management transparently
  • Simpler implementation
  • Sufficient for most use cases
Client-Side (CSE)
  • You encrypt before sending to AWS
  • Data encrypted end-to-end
  • AWS never sees plaintext data
  • You control encryption logic
  • Required for highest security / compliance

The AWS Encryption SDK implements envelope encryption client-side with best practices built in: authenticated encryption, data key caching, multiple master key support, and message format that stores encrypted data keys alongside ciphertext.

Diagram 8-2 Β· Zero-Trust Encryption β€” Defense in Depth Layers
LAYER 5: NETWORK VPC Endpoint Policy + Security Groups LAYER 4: IDENTITY IAM Policy (kms:Decrypt + resource ARN) LAYER 3: KEY POLICY kms:ViaService + kms:CallerAccount conditions LAYER 2: ENCRYPTION CONTEXT Must provide correct key-value pairs πŸ” ENCRYPTED DATA βœ“ From VPC endpoint βœ“ IAM allows kms:* βœ“ Key policy allows βœ“ Context matches ALL layers must pass simultaneously Β· Compromise any single layer β†’ still protected by others
Five layers of defense β€” attacker must breach ALL simultaneously to access data
Pattern 7 β€” Compliance Governance with AWS Config Pro

AWS Config Rules for KMS

  • cmk-backing-key-rotation-enabled
  • kms-cmk-not-scheduled-for-deletion
  • s3-bucket-server-side-encryption-enabled
  • encrypted-volumes
  • rds-storage-encrypted

SCP Guardrails (Organizations)

  • Deny kms:DisableKey for non-security roles
  • Deny kms:ScheduleKeyDeletion broadly
  • Require CMK for all S3/EBS/RDS encryption
  • Deny kms:PutKeyPolicy without approval tag
  • Enforce encryption context on API operations
Diagram 8-3 Β· KMS Decision Framework β€” Choosing Your Architecture
What are your requirements? Standard Use Case AWS service encryption Audit + access control Standard KMS Customer Managed CMK Compliance Need FIPS L3 / single-tenant HSM Direct HSM control Custom Key Store CloudHSM-backed Sovereignty / Kill Switch Keys cannot be in AWS Need revocation ability External Key Store XKS Proxy ADDITIONAL DECISIONS Multi-Region DR? β†’ Multi-Region Keys Key generated on-prem? β†’ BYOK (Imported) External party encrypts? β†’ Asymmetric Key High throughput? β†’ Data Key Caching Β· S3 at scale? β†’ Bucket Keys Β· Revoke all? β†’ Disable CMK
Standard (99%) β†’ Custom Key Store (compliance) β†’ XKS (sovereignty) + additional overlays as needed
Quick Reference β€” KMS Architecture Cheat Sheet Core
ScenarioPatternKey Chapter
Encrypt large filesEnvelope encryption + GenerateDataKeyCh04
S3 encryption at scaleSSE-KMS + Bucket Keys enabledCh06
Cross-account data sharingKey policy + IAM policy (dual auth)Ch05
Global application DRMulti-Region keysCh07
External client encryptsAsymmetric RSA key (public key distributed)Ch03
CI/CD secretsSecrets Manager + CMK + grantsCh08
Regulatory single-tenant HSMCustom Key Store (CloudHSM)Ch07
Data sovereigntyExternal Key Store (XKS)Ch07
Prevent accidental deletionSCP deny + separate admin roleCh05
Audit all key usageCloudTrail + CloudWatch alarmsCh06
🎯 Exam Tips β€” Architecture Patterns
  • "Centralized key management" β†’ Dedicated security account + cross-account key policies.
  • "Different encryption per data classification" β†’ Multiple CMKs, restrict decrypt by role per classification.
  • "DR for encrypted data without re-encryption" β†’ Multi-Region keys.
  • "Ensure all resources are encrypted" β†’ AWS Config rules + SCP deny unencrypted resource creation.
  • "Client-side encryption before upload" β†’ AWS Encryption SDK with KMS master key provider.
  • "Zero-trust data access" β†’ Layer: VPC endpoint + IAM + Key Policy + Encryption Context + Grants.
  • "Prevent any admin from accessing data" β†’ Nitro Enclaves with KMS attestation conditions.
Chapter 08 Summary β€” Architecture Patterns
  • Multi-Account: Central security account owns keys. Workload accounts get scoped usage. One revocation point.
  • Data Lake: Different CMKs per classification. KMS = secondary access control beyond S3 policies.
  • Cross-Region DR: Multi-Region keys β†’ data decryptable immediately after failover.
  • Zero Trust: 5 layers (network + identity + key policy + context + grants). Must pass ALL.
  • CI/CD Secrets: Secrets Manager + dedicated CMK + encryption context binding + ephemeral grants.
  • Client-Side: AWS Encryption SDK. Encrypt before AWS sees data. For highest compliance.
  • Governance: AWS Config rules + SCPs enforce encryption standards organization-wide.
Chapter 08 β€” Key Takeaway

KMS is not just a service β€” it's the foundation of your entire AWS security architecture. Centralize key management, use multiple CMKs for blast radius reduction, layer defenses, and treat KMS as the control plane for data access. Every architecture decision about "who can access what data" should have a KMS component.

Chapter 08 of 08 β€” Complete
KMS Glossary β€” Quick Reference Reference
TermDefinition
CMKCustomer Master Key β€” the logical KMS key resource you create and manage
Key MaterialThe actual cryptographic bytes used for encryption/decryption
Backing KeyThe underlying key material (multiple exist over time with rotation)
Data KeyA key generated by KMS for local envelope encryption (not stored in KMS)
Envelope EncryptionPattern: encrypt data key with CMK, then use data key to encrypt data locally
Encryption ContextKey-value pairs cryptographically bound to ciphertext; required for decryption
Key PolicyResource-based JSON policy attached to each KMS key (mandatory, max 32 KB)
GrantTemporary, programmatic permission delegation for KMS key access
AliasFriendly name pointer to a CMK (e.g., alias/prod-key); updateable without code changes
Custom Key StoreKMS key backed by your own dedicated CloudHSM cluster
XKSExternal Key Store β€” key material stored outside AWS entirely (via XKS Proxy)
BYOKBring Your Own Key β€” import externally-generated key material into KMS
Multi-Region KeyKey replicated across regions with same material (mrk- prefix)
FIPS 140-2US government security standard for cryptographic modules (Level 2 = KMS, Level 3 = CloudHSM)
HSMHardware Security Module β€” tamper-resistant hardware for key storage and operations
S3 Bucket KeyIntermediate cached key that reduces KMS API calls by 99% for S3 SSE-KMS
Further Reading β€” Related AWS Services Reference
ServiceRelationship to KMSWhen to Use
AWS CloudHSMAlternative (dedicated HSM for KMS custom key store)Regulatory requiring single-tenant HSM / FIPS Level 3
AWS Certificate Manager (ACM)Different purpose (TLS certificates, not data-at-rest)HTTPS termination at ALB, CloudFront, API Gateway
AWS Secrets ManagerUses KMS for envelope encryption of secretsStore and rotate database passwords, API keys
SSM Parameter StoreUses KMS for SecureString encryptionApplication configuration with optional encryption
AWS Nitro EnclavesUses KMS with attestation conditionsProcess sensitive data with hardware-level isolation
AWS Encryption SDKClient-side library that wraps KMS for envelope encryptionEncrypt before sending to AWS; multi-key, caching built in
ACM Private CADifferent purpose (internal X.509 certificates)Internal mTLS, code signing, IoT device identity
Official Documentation

AWS KMS Developer Guide β€” the authoritative reference for all APIs, quotas, and service integrations. AWS Encryption SDK docs β€” for client-side envelope encryption implementation. AWS Security Blog β€” for architecture patterns and best practices.