Encrypt Data with AWS KMS: Keys, Policies, Rotation

Khimananda Oli 8 min read Database
Encrypt Data with AWS KMS: Keys, Policies, Rotation

By Khimananda Oli | Last reviewed: August 2026

Managing secrets securely is the foundation of any compliant cloud architecture, yet many teams still store credentials in plain text or misconfigure access controls. To properly encrypt data with AWS KMS: Keys, Policies, Rotation, you must understand the relationship between managed keys, resource-based policies, and automated lifecycle management. This guide provides the exact configuration patterns I use to secure production workloads and pass SOC 2 audits without slowing down development velocity.

How Do You Choose Between AWS Managed and Customer Managed KMS Keys?

Before you write a single line of Terraform or click through the console, you must decide on the key ownership model. This decision dictates your compliance posture and operational flexibility. When you encrypt data with AWS KMS: Keys, Policies, Rotation, the choice between AWS-owned, AWS-managed, and customer-managed keys determines whether you can define custom policies, track usage via CloudTrail, or rotate keys on your own schedule.

AWS Owned KeyNo VisibilityNo Policy ControlAuto-Rotated by AWSNot Audit ReadyAWS Managed KeyCloudTrail LogsRead-Only PolicyAnnual Auto-RotationLimited ComplianceCustomer Managed KeyFull CloudTrail AuditCustom Key PolicyConfigurable RotationSOC2 / ISO 27001 Ready
AWS KMS key hierarchy: Only Customer Managed Keys provide full policy control and audit capabilities required when you encrypt data with AWS KMS for compliance.

In practice, I default to Customer Managed Keys (CMKs) for almost every production workload. While AWS-managed keys are free and require zero setup, they lock you out of defining who can use the key beyond basic service integration. If you are preparing for an ISO 27001 certification or need to demonstrate least-privilege access during a SOC 2 audit, CMKs are non-negotiable. They allow you to attach resource-based policies that restrict decryption to specific IAM roles, VPC endpoints, or even time-bound conditions.

For teams just starting their cloud journey, perhaps following our guide to launching secure EC2 instances, AWS-managed keys are an acceptable starting point. However, migrate to CMKs before handling sensitive user data or financial records. The cost difference is minimal ($1/month per key), but the security and compliance value is exponential.

How Do You Configure Least-Privilege KMS Key Policies?

A common mistake I see in security reviews is treating KMS key policies as optional. Unlike IAM policies, which are identity-based, KMS key policies are resource-based and serve as the primary authorization mechanism. Even if an IAM user has kms:Decrypt permissions, they cannot decrypt ciphertext unless the key policy explicitly allows it. This dual-control model is what makes AWS KMS powerful for governance.

Defining Granular Access Controls

When you configure a key policy, avoid wildcards. Grant only the specific actions required for each principal. For application servers that need to read encrypted configuration from S3 or RDS, grant kms:Decrypt and kms:DescribeKey. Reserve kms:Encrypt for services that generate new data. Administrative actions like kms:CreateGrant or kms:DisableKey should be restricted to a dedicated break-glass role.

{
    "Version": "2012-10-17",
    "Id": "app-production-key-policy",
    "Statement": [
        {
            "Sid": "Enable Root Account Management",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:root"
            },
            "Action": "kms:*",
            "Resource": "*"
        },
        {
            "Sid": "Allow App Role Decryption Only",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:role/AppServerRole"
            },
            "Action": [
                "kms:Decrypt",
                "kms:DescribeKey"
            ],
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "kms:CallerAccount": "123456789012"
                }
            }
        }
    ]
}

This policy ensures that even if the AppServerRole is compromised, the attacker cannot re-encrypt data with this key or modify the key itself. For deeper context on identity boundaries, refer to our article on AWS IAM best practices for least-privilege access. Always test policies in a staging environment first; a misconfigured key policy can permanently lock you out of your data.

How Does Envelope Encryption Work in AWS KMS?

You never send raw gigabytes of database dumps or log files directly to KMS. The service has a 4KB payload limit for direct encryption. Instead, AWS uses envelope encryption, a pattern where KMS protects a data key, and that data key protects your actual content. Understanding this flow is critical for debugging latency issues and designing scalable architectures.

ApplicationGenerates PlaintextData Key (DEK)Encrypts Payload LocallyAWS KMS CMKProtects DEK OnlyRequest DEKEncrypted DEK StoredEncrypted Blob + Encrypted DEK
Envelope encryption flow: The plaintext data key never leaves memory, ensuring high performance when you encrypt data with AWS KMS at scale.

The process works as follows:

  1. Your application calls GenerateDataKey. KMS returns two versions: a plaintext key (for immediate local encryption) and an encrypted copy (protected by your CMK).
  2. The application uses the plaintext key to encrypt your large dataset locally using AES-256-GCM or similar.
  3. The plaintext key is wiped from memory immediately after use.
  4. The encrypted data and the encrypted data key are stored together in S3, EBS, or your database.
  5. To decrypt, you send the encrypted data key back to KMS via Decrypt, receive the plaintext key transiently, and decrypt the payload locally.

This architecture means KMS only handles small cryptographic operations, not bulk data transfer. It also explains why network latency to the KMS endpoint matters. If you are building serverless applications where cold starts are a concern, consider caching decrypted data keys securely in memory for short durations, or explore the AWS Encryption SDK’s built-in caching features. For teams managing containerized workloads, our Docker containerization guide covers integrating this pattern into application startup routines safely.

How Do You Automate KMS Key Rotation Without Breaking Applications?

Compliance frameworks typically mandate cryptographic key rotation every 365 days. Manual rotation is error-prone and risky. When you encrypt data with AWS KMS: Keys, Policies, Rotation, always enable automatic rotation for symmetric CMKs. AWS handles this transparently by generating new backing key material while keeping the same key ID and metadata.

Understanding Rotation Mechanics

Automatic rotation does not re-encrypt your existing data. Previous versions of the backing key remain available for decryption indefinitely. This is crucial: enabling rotation will not cause downtime or require application redeployment. New encryption operations automatically use the latest backing key version.

# Enable automatic rotation via AWS CLI
aws kms enable-key-rotation \
    --key-id arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \
    --rotation-period-in-days 180

# Verify rotation status
aws kms get-key-rotation-status \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Note that asymmetric keys and HMAC keys do not support automatic rotation. For those, you must implement manual rotation procedures with careful coordination. Also, imported key material cannot be auto-rotated; if compliance requires rotation for imported keys, you must manage the lifecycle externally.

FeatureSymmetric CMKAsymmetric CMKAWS Managed Key
Automatic Rotation SupportYes (configurable 90–2560 days)NoYes (fixed 365 days)
Custom Key PolicyYesYesNo
Previous Versions RetainedIndefinitelyN/AIndefinitely
Use CaseData at rest, envelope encryptionDigital signatures, TLS offloadDefault service encryption
Compliance SuitabilitySOC 2, ISO 27001, HIPAAPKI, code signingBasic workloads only

What Are Common Pitfalls When Implementing KMS in Production?

Even experienced teams stumble on subtle KMS behaviors. One frequent issue is confusing key deletion with disabling. Disabling a key is reversible and safe for testing revocation. Scheduling deletion has a mandatory 7–30 day waiting period, but once executed, recovery is impossible. Always set up CloudWatch alarms for ScheduledKeyDeletion events to catch accidental deletions before they become catastrophes.

Another pitfall is over-relying on cross-region replication. KMS keys are regional resources. If you replicate encrypted data from us-east-1 to ap-southeast-1 for disaster recovery, you must also replicate the CMK or use multi-region keys introduced in recent years. Multi-region keys simplify this but add complexity to key policies and audit trails. Document your replication strategy explicitly in your infrastructure-as-code repositories, ideally using patterns from our Terraform practical guide.

Finally, monitor your KMS usage. High volumes of Decrypt calls can indicate either legitimate traffic spikes or an active breach attempting to exfiltrate data. Set up CloudWatch metrics and alerts for anomalous API call patterns. Combine this with VPC Flow Logs and CloudTrail insights to build a defense-in-depth observability stack that satisfies both operational needs and auditor requirements.

Start: Need EncryptionRequire Custom Policy or Audit?NoYesAWS Managed KeyCustomer Managed KeyNeed Cross-Region Replication?NoYesSingle-Region CMKMulti-Region CMK
Decision tree for choosing the right KMS key configuration when you encrypt data with AWS KMS in production environments.

Securing Your Data Lifecycle with Confidence

Implementing encryption correctly is about more than checking a compliance box; it is about building trust with your users and resilience into your platform. When you encrypt data with AWS KMS: Keys, Policies, Rotation, you establish a cryptographic foundation that scales with your business and withstands scrutiny from auditors and attackers alike. Start with customer-managed keys, enforce strict policies, automate rotation, and validate your assumptions continuously through monitoring and testing.

If your team needs help designing a KMS strategy that aligns with your specific compliance requirements or application architecture, reach out to discuss your infrastructure security needs. Whether you are preparing for your first SOC 2 audit or optimizing costs across a multi-account organization, getting encryption right from the start prevents expensive rework later.

Frequently Asked Questions

Symmetric keys use a single secret for both encryption and decryption, ideal for encrypting data at rest. Asymmetric keys use public-private pairs for digital signatures or encrypting small payloads outside AWS. Most AWS service integrations require symmetric keys for envelope encryption workflows.

AWS managed keys are free. Customer managed keys cost one dollar per key monthly plus four cents per ten thousand API requests. Custom key stores add significant infrastructure fees. Costs scale with key count and request volume, not encrypted data size.

Yes, enable automatic rotation in the console or via CLI to rotate backing key material annually while preserving the key ID. Previous versions remain active for decryption. Manual rotation requires creating new keys and updating aliases, which breaks backward compatibility without application changes.

Attach a resource-based policy defining allowed principals, actions like kms:Encrypt, and conditions such as source VPC or tag values. Always include the root account principal to prevent lockout. Combine with IAM policies for defense-in-depth access control across accounts.

No. Automatic rotation only updates the underlying key material used for future operations. Existing ciphertext remains decryptable because KMS retains prior key versions. You must manually trigger re-encryption if compliance mandates fresh cryptographic protection for legacy objects.

The key enters a pending deletion state lasting seven to thirty days. During this window, disable the cancellation using the CancelKeyDeletion API. After the period expires, all encrypted data becomes permanently unrecoverable. Always test recovery procedures before scheduling production key deletions.

No. AWS cannot extract plaintext from your customer managed keys or access encrypted data. Key material never leaves KMS hardware security modules unencrypted. Only authorized principals defined in your key policy can perform cryptographic operations on protected resources.

Enable CloudTrail logging to capture all KMS API calls including Encrypt, Decrypt, and GenerateDataKey events. Filter logs by event name and user identity. Set up CloudWatch alarms for unauthorized access attempts or unusual usage patterns to detect potential compromise early.

Use customer managed keys when you need custom policies, automatic rotation control, or cross-account sharing. Choose AWS managed keys for simple service integration without administrative overhead. Customer managed keys provide granular audit trails and compliance evidence that managed keys cannot offer.

Generate a unique data key via KMS, encrypt your payload locally with its plaintext copy, then store only the encrypted data key alongside ciphertext. Discard the plaintext immediately. This minimizes KMS API calls and keeps large dataset encryption performant and cost-effective.

Yes, create an external key and upload wrapped key material using RSA-OAEP padding. You manage the original key lifecycle externally. Imported keys do not support automatic rotation. This satisfies bring-your-own-key compliance requirements while maintaining AWS integration capabilities.

Verify the caller has kms:Decrypt permission in both IAM and the key policy. Check condition keys like kms:ViaService or aws:SourceVpc match your request context. Confirm the key is enabled and not in pending deletion state. Test with aws sts get-caller-identity first.

No. KMS keys are regional resources and cannot replicate across regions. Create separate keys in each region where encrypted data resides. For multi-region disaster recovery, configure multi-Region keys that share the same key ID but maintain independent regional endpoints.

Add StringEquals conditions for kms:RequestTag keys in your key policy. Require specific tag values during CreateGrant or GenerateDataKey calls. Reject non-compliant requests automatically. Tags enable attribute-based access control without managing individual principal permissions at scale.

Yes. All KMS HSMs operate in FIPS 140-2 Level 2 validated mode. Use FIPS endpoints explicitly in SDK configuration for compliant traffic routing. Audit reports are available through AWS Artifact. Validation covers key generation, storage, and cryptographic operation boundaries.