Thuta Learning
AWS Advanced
SecurityDevOpsAdvanced

KMS and Secrets Manager: Managing Keys and Secrets

AWS AdvancedLesson 2450 min

What you'll walk away with

  • Tell apart AWS managed and customer managed keys, and explain why the key policy is the root of access
  • Perform envelope encryption with GenerateDataKey and explain why the plaintext key is never stored
  • Use automatic rotation, multi-Region keys and encryption context correctly
  • Choose between Secrets Manager (rotation, cross-account) and SSM Parameter Store SecureString

Explain it simply

Explain it simply

Think of AWS KMS as a master key locked inside a bank vault. That key never leaves the vault. When you want to lock your data, you ask the bank for a small 'data key', lock your box with it, then seal the data key in an envelope locked by the master key and tape it to the box.

The key policy decides who may enter the bank and open that envelope. Secrets Manager is a key cabinet for things like database passwords: it stores them encrypted with KMS, and it can change the passwords automatically on a schedule.

Problem → Why → Solution

The problem: secrets everywhere, and no idea who uses the keys

At a startup the database password lives in Lambda environment variables, in CI/CD variables and in .env files on developer laptops. It has not changed in two years, because nobody knows which services would break if it did. When a developer leaves, there is not even a list of the places where the password would need changing.

On the encryption side, every bucket and EBS volume uses AWS managed keys, so when a large customer asks 'who can decrypt our data, and can we have a dedicated key just for our data?', there is no answer.

what-went-wrong.sh
# BAD: the password is visible to anyone who can read the function configuration,
# it is copied into every deploy, and rotating it means redeploying everything.
aws lambda update-function-configuration \
  --function-name orders-api \
  --environment "Variables={DB_USER=app_user,DB_PASSWORD=Summer2024!}"

Secrets need one home, and keys need a policy

The more places a secret is copied to, the more likely it leaks and the harder it is to rotate. Keep the secret in one place and have applications read it at runtime with IAM permissions, and rotation no longer touches the application. Customer managed keys let you control, and prove through key policies and CloudTrail logs, exactly who decrypts what.

Core concept: key types, key policies, envelope encryption

Key typeWho controls itNotes
AWS owned keyAWS (not visible in your account)Default for some services; no policy or logs for you
AWS managed key (aws/s3, aws/ebs...)AWS, created in your accountPolicy cannot be edited; rotates yearly; no cross-account use
Customer managed keyYouYou own the policy, grants, rotation and deletion; monthly fee

Every KMS key has exactly one key policy, and it is the root of access. For most AWS services an IAM policy alone can grant access, but in KMS an IAM policy does nothing unless the key policy allows it. The default key policy contains a statement giving kms:* to the account principal (arn:aws:iam::111122223333:root), which means 'trust IAM policies in this account'; it does not mean only the root user.

Grants are the third mechanism: they let a principal perform certain operations temporarily without editing the key policy. AWS services such as EBS create grants automatically to use a key on your behalf and retire them when done.

Envelope encryption
Encrypting data locally with a data key, and encrypting that data key with a KMS key. The encrypted data key is stored with the encrypted data, and the plaintext data key is never stored.

The KMS Encrypt API accepts at most 4 KB of plaintext, and sending gigabyte files over the network to KMS would be slow and expensive anyway. So you call GenerateDataKey and get two copies of a data key: a plaintext copy and a copy encrypted under your KMS key. You encrypt the data in memory with the plaintext copy, discard it immediately, and store only the encrypted copy with the data. To read it back, you send the encrypted data key to KMS Decrypt.

The encryption context is a set of non-secret key-value pairs supplied at encryption time. Decryption requires the exact same pairs, they are recorded in CloudTrail, and key policy conditions can use them, for example allowing decryption only when the context contains tenant=acme.

text
ENVELOPE ENCRYPTION WITH GENERATEDATAKEY
----------------------------------------
  WRITE                                    READ
  app --GenerateDataKey(ctx)--> KMS        app --Decrypt(blob, ctx)--> KMS
        <-- plaintext key + blob --              <-- plaintext key ------
   |                                        |
   | AES-GCM encrypt data locally           | AES-GCM decrypt locally
   | then DISCARD plaintext key             | then DISCARD plaintext key
   v                                        v
  +--------------------------------+       KMS key itself never leaves
  | stored: ciphertext + blob + ctx|       KMS; every call is checked
  +--------------------------------+       against the key policy
Mental model: lock the key with a key
  1. GenerateDataKey: plaintext + blob
  2. Encrypt data locally, drop plaintext
  3. Store blob next to the ciphertext
  4. Decrypt blob via KMS to read again
  5. Key policy gates every KMS call

The KMS key never leaves KMS. You only ever handle data keys, and their plaintext must never be written to disk.

Pattern: a least-privilege key policy

key-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EnableIamPoliciesInThisAccount",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111122223333:root" },
      "Action": "kms:*",
      "Resource": "*"
    },
    {
      "Sid": "KeyAdministratorsCannotUseTheKey",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111122223333:role/KeyAdmins" },
      "Action": [
        "kms:DescribeKey",
        "kms:EnableKeyRotation",
        "kms:PutKeyPolicy",
        "kms:ScheduleKeyDeletion",
        "kms:CancelKeyDeletion",
        "kms:TagResource"
      ],
      "Resource": "*"
    },
    {
      "Sid": "InvoiceServiceOnlyForTenantAcme",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::111122223333:role/invoice-service" },
      "Action": ["kms:GenerateDataKey", "kms:Decrypt"],
      "Resource": "*",
      "Condition": {
        "StringEquals": { "kms:EncryptionContext:tenant": "acme" }
      }
    }
  ]
}

Inside a key policy, "Resource": "*" means 'this key'. The first statement keeps IAM policies working; removing it risks a key nobody can manage. The second gives key administrators management rights but no right to decrypt data (separation of duties). The third lets invoice-service create and decrypt data keys only when the encryption context contains tenant=acme. Apply it with aws kms put-key-policy --key-id $KEY_ID --policy file://key-policy.json.

The envelope encryption flow with boto3

This script uses a customer managed key with the alias alias/app-data to show every step of envelope encryption: generating a data key, storing only the encrypted copy, discarding the plaintext, decrypting with KMS, and being refused when the encryption context is wrong. Create the key beforehand with aws kms create-key and create-alias.

The step that encrypts the payload with AES-GCM is left out so the script runs with boto3 alone. In production use the AWS Encryption SDK, which generates the data key, encrypts, and packs the encrypted key into its message format correctly for you.

envelope.py
import base64

import boto3
from botocore.exceptions import ClientError

kms = boto3.client("kms", region_name="us-east-1")
CONTEXT = {"tenant": "acme", "purpose": "invoice-pdf"}

# 1. Ask KMS for a fresh data key: a plaintext copy + an encrypted copy
resp = kms.generate_data_key(
    KeyId="alias/app-data", KeySpec="AES_256", EncryptionContext=CONTEXT
)
plaintext_key = resp["Plaintext"]
print("plaintext data key length:", len(plaintext_key), "bytes")

# 2. Real code encrypts the payload locally here with AES-GCM using
#    plaintext_key (for example through the AWS Encryption SDK).

# 3. Store ONLY the encrypted data key next to the encrypted payload
record = {
    "encrypted_key": base64.b64encode(resp["CiphertextBlob"]).decode(),
    "context": CONTEXT,
}
print("stored fields:", sorted(record))
print("plaintext key in record:",
      base64.b64encode(plaintext_key).decode() in str(record))

# Demo only: keep a copy to prove the round trip, then drop the key
original_key = bytes(plaintext_key)
del plaintext_key, resp["Plaintext"]

# 4. Later: KMS decrypts the data key (needs kms:Decrypt + the same context)
blob = base64.b64decode(record["encrypted_key"])
restored = kms.decrypt(CiphertextBlob=blob, EncryptionContext=record["context"])
print("data key recovered:", restored["Plaintext"] == original_key)
print("same KMS key used:", restored["KeyId"] == resp["KeyId"])

# 5. A different encryption context -> KMS refuses to decrypt
try:
    kms.decrypt(CiphertextBlob=blob,
                EncryptionContext={"tenant": "other", "purpose": "invoice-pdf"})
except ClientError as err:
    print("wrong context:", err.response["Error"]["Code"])

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. GenerateDataKeykms.generate_data_key(KeyId="alias/app-data", KeySpec="AES_256", ...)

    Returns one AES-256 data key (32 bytes) in two forms: Plaintext and CiphertextBlob. The caller needs kms:GenerateDataKey on this key.

  2. Store only the blobrecord = {"encrypted_key": ..., "context": CONTEXT}

    The stored record holds only the encrypted data key and the context. 'plaintext key in record: False' proves the plaintext key was never stored.

  3. Drop the plaintextdel plaintext_key, resp["Plaintext"]

    Drop every reference to the plaintext key once it has been used. Python cannot wipe memory precisely, but the point is to keep it out of logs, disk and caches.

  4. Decrypt with the same contextkms.decrypt(CiphertextBlob=blob, EncryptionContext=record["context"])

    The blob already records which key encrypted it, so KeyId is optional for symmetric keys (passing it is safer). A different context results in InvalidCiphertextException.

You should see
plaintext data key length: 32 bytes
stored fields: ['context', 'encrypted_key']
plaintext key in record: False
data key recovered: True
same KMS key used: True
wrong context: InvalidCiphertextException

Rotation, multi-Region keys and key deletion

Customer managed symmetric keys support automatic rotation: once every 365 days by default, adjustable between 90 and 2,560 days, plus on-demand rotation when you need it. Rotation creates new key material but keeps the key ID, ARN, aliases and policy, and the old material is retained so old data still decrypts. Existing ciphertexts are not re-encrypted, which is why no application change is needed.

Multi-Region keys (key IDs starting with mrk-) are keys in several Regions that share the same key material and key ID. Data encrypted in one Region can be decrypted in another without a cross-Region call, which helps DR and global tables. But each replica is a separate resource with its own key policy, grants and aliases, and an existing single-Region key cannot be converted into a multi-Region key.

Deleting a key happens only after a 7 to 30 day waiting period, and afterwards all data encrypted under it is unreadable forever. If in doubt, disable the key and watch CloudTrail for anyone still using it.

create-key.sh
KEY_ID=$(aws kms create-key \
  --description "Invoice data key" \
  --key-usage ENCRYPT_DECRYPT \
  --key-spec SYMMETRIC_DEFAULT \
  --query KeyMetadata.KeyId --output text)

aws kms create-alias --alias-name alias/app-data --target-key-id "$KEY_ID"
aws kms put-key-policy --key-id "$KEY_ID" --policy file://key-policy.json
aws kms enable-key-rotation --key-id "$KEY_ID" --rotation-period-in-days 180
aws kms get-key-rotation-status --key-id "$KEY_ID"

# Multi-Region: create the primary, then a replica in another Region
MRK_ID=$(aws kms create-key --multi-region \
  --description "Global orders key" \
  --query KeyMetadata.KeyId --output text)
aws kms replicate-key --key-id "$MRK_ID" --replica-region eu-west-1

Secrets Manager vs Parameter Store SecureString

Secrets Manager stores secrets encrypted with KMS and tracks versions with staging labels (AWSCURRENT, AWSPENDING, AWSPREVIOUS). Its main strength is rotation: a Lambda function runs four steps, createSecret, setSecret, testSecret and finishSecret, to generate a new password, set it in the database, test it, and only then move the AWSCURRENT label. For RDS and Aurora master passwords there is managed rotation run by RDS itself, so no Lambda is needed.

To let another account read a secret you need three things: a resource policy on the secret, a key policy on a customer managed key allowing that account kms:Decrypt, and an IAM policy in the reading account. The default aws/secretsmanager key cannot be used cross-account, so a customer managed key is required.

NeedSecrets ManagerParameter Store SecureString
Built-in rotationYes (Lambda or managed)No; build it yourself
Cross-account accessYes, via a resource policyNeeds advanced tier and sharing; more complex
CostPer secret per month plus API callsStandard parameters free; advanced tier paid
Best forDB credentials and API keys that must rotateConfig and secrets that do not rotate

Calling the API on every Lambda invocation adds latency and cost. The code below reads the secret at most once every five minutes per execution environment; after a rotation, the new password is picked up as soon as the cache expires. (The AWS Parameters and Secrets Lambda Extension can do this caching for you as well.)

secret_cache.py
import json
import time

import boto3

secrets = boto3.client("secretsmanager", region_name="us-east-1")
SECRET_ID = "prod/orders/db"
CACHE_SECONDS = 300
_cache = {"value": None, "fetched_at": 0.0}
api_calls = 0


def get_db_credentials():
    """Fetch the secret at most once per 5 minutes per execution environment."""
    global api_calls
    if _cache["value"] is None or time.time() - _cache["fetched_at"] > CACHE_SECONDS:
        resp = secrets.get_secret_value(SecretId=SECRET_ID)  # AWSCURRENT version
        _cache.update(value=json.loads(resp["SecretString"]), fetched_at=time.time())
        api_calls += 1
    return _cache["value"]


def lambda_handler(event, context):
    creds = get_db_credentials()
    return {"connect_as": creds["username"]}


if __name__ == "__main__":
    for _ in range(3):
        print(lambda_handler({}, None))
    print("Secrets Manager API calls:", api_calls)

In production

How teams use it in production

Multi-account organizations split customer managed keys by data sensitivity: per application, per environment (prod/dev), and dedicated keys for large customers. Key policies are written in IaC with key administrators separated from key users, and an SCP blocks kms:ScheduleKeyDeletion for everyone except the security team. Because CloudTrail records each Decrypt call together with its encryption context, they can show auditors which service decrypted which tenant's data.

For secrets, all database credentials live in Secrets Manager and rotate every 30 to 90 days. Applications get only the secret ARN in an environment variable and read the value at runtime. Plain configuration such as feature flags and endpoint URLs goes into the Parameter Store standard tier.

  • Alarms: an EventBridge rule on CloudTrail events such as ScheduleKeyDeletion, DisableKey and PutKeyPolicy notifies the security team immediately.
  • Rotation monitoring: when a Secrets Manager rotation fails (for example in the testSecret step), an EventBridge alert fires and someone checks that AWSCURRENT still holds a working password.
  • Access reviews: IAM Access Analyzer regularly checks key policies and secret resource policies for unintended access from outside accounts.

Common mistakes

Common mistakes

Removing the account principal statement from the key policy

Remove the arn:aws:iam::...:root statement in the name of 'least privilege', leave a single role, and IAM policies stop working. If that role is ever deleted, nobody can manage the key and you need AWS Support. PutKeyPolicy rejects such a lockout policy by default, but the safety check can be bypassed, so never use that flag.

Logging or storing the plaintext data key

Log the whole GenerateDataKey response while debugging and the plaintext key lands in CloudWatch Logs, defeating envelope encryption entirely. Never log the response; store only the CiphertextBlob.

Sharing a secret encrypted with aws/secretsmanager

Even with a correct resource policy, a secret encrypted with the AWS managed key cannot be decrypted from another account, so you get AccessDenied. Encrypt cross-account secrets with a customer managed key and allow the other account in its key policy.

Rotating while the application caches the password forever

Read the password once at container start and hold it forever, and new connections fail after the next rotation. Give the cache a TTL, and on an authentication error re-read the secret and retry.

💰 Cost & Cleanup

A customer managed KMS key has a monthly fee (prorated hourly) plus charges for API requests (the free tier includes a monthly request allowance). AWS managed keys have no monthly fee but requests are still charged. Secrets Manager charges per secret per month plus per 10,000 API calls, while Parameter Store standard parameters are free. Check the pricing pages for exact figures. After the lab, schedule the key for deletion (minimum 7-day wait) and delete the secret and parameter.

Clean up when you are done

cleanup.sh
aws secretsmanager delete-secret \
  --secret-id prod/orders/db \
  --force-delete-without-recovery

aws ssm delete-parameter --name /orders/api-key

KEY_ID=$(aws kms describe-key --key-id alias/app-data \
  --query KeyMetadata.KeyId --output text)
aws kms delete-alias --alias-name alias/app-data
aws kms schedule-key-deletion --key-id "$KEY_ID" --pending-window-in-days 7

Mini challenge

Protect a SecureString parameter with your own key

Create a customer managed key, enable rotation on it, and store a SecureString parameter encrypted with that key. Then read it back decrypted.

  • Create a symmetric key with the alias alias/app-data
  • Enable automatic rotation every 180 days and check its status
  • Store /orders/api-key as a SecureString encrypted with alias/app-data
  • Read it back with --with-decryption and see the value

Expected: get-key-rotation-status shows KeyRotationEnabled: true and RotationPeriodInDays: 180, and get-parameter returns the plaintext value. Without --with-decryption you get only the encrypted value.

Show hint

Use --type SecureString with --key-id alias/app-data on put-parameter. For the rotation period, use --rotation-period-in-days on enable-key-rotation.

Show solution
solution.sh
KEY_ID=$(aws kms create-key \
  --description "Orders config key" \
  --query KeyMetadata.KeyId --output text)
aws kms create-alias --alias-name alias/app-data --target-key-id "$KEY_ID"

aws kms enable-key-rotation --key-id "$KEY_ID" --rotation-period-in-days 180
aws kms get-key-rotation-status --key-id "$KEY_ID"

aws ssm put-parameter \
  --name /orders/api-key \
  --type SecureString \
  --key-id alias/app-data \
  --value "sk-test-0123456789"

aws ssm get-parameter --name /orders/api-key --with-decryption \
  --query Parameter.Value --output text

Quick quiz 1 / 3

A role's IAM policy allows kms:Decrypt on a customer managed key, but calls still get AccessDenied. What is the most likely cause?

Quick quiz 2 / 3

You need to protect a 2 GB file with a KMS key. Why use envelope encryption?

Quick quiz 3 / 3

An Aurora user's password must change automatically every 30 days, and an analytics account must also read it. What do you use?

What to remember

  • AWS managed keys are simple but their policy cannot be edited or shared cross-account; use customer managed keys when you need control.
  • The key policy is the root of access: IAM policies work only if the key policy trusts the account, and grants are for temporary delegation.
  • Envelope encryption: GenerateDataKey, encrypt locally, store only the encrypted data key, and always pass an encryption context.
  • Rotation changes key material without changing the key ID, and multi-Region keys let data be decrypted across Regions.
  • Keep secrets that must rotate or be shared across accounts in Secrets Manager, and plain config in Parameter Store.

AWS KMS concepts — AWS Documentation

Key policies in AWS KMS — AWS Documentation

What is AWS Secrets Manager? — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

KMS and Secrets Manager: Managing Keys and Secrets | Thuta Learning