TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท security ยท encryption ยท kms ยท secrets

AWS KMS and Secrets Manager

How AWS keeps encryption keys and credentials safe. KMS keys live in hardware security modules and never leave them, data is protected by envelope encryption with data keys, and Secrets Manager stores credentials encrypted under KMS and rotates them on a schedule.

16 min6 animations

๐Ÿ“š Builds on๐Ÿชช AWS IAM: users, roles and policies

๐Ÿ–จ๏ธ Cheat sheet

A vault whose master keys never leave

Ana runs a shop, and some of what she keeps is private: customers' card numbers, the till code, her suppliers' contracts. She can't hide it all under the counter, so she uses the bank's vault.

The vault holds master keys. Each one hangs on its own hook deep inside, behind steel walls, and here's the important part: a master key never leaves the vault. Not for Ana, not for the bank staff. If Ana wants something locked, she hands a small envelope to the vault clerk through the window. The clerk locks it inside, with Ana's master key, and passes back the locked envelope. To open it again, she hands it back and the clerk unlocks it, inside.

Why so strict? Because a key that never goes out can't be copied, dropped or stolen on the way home. The worst a thief can do is steal locked envelopes, and those are useless without the vault.

Ana can use two kinds of master key. The bank keeps a ready-made one for each service it runs for her, like the storage room, with rules the bank sets. Or she can order a key in her own name, write its rules herself, switch it off, or even have it destroyed.

The clerk also writes every visit in the vault's visitor book: who came, which key, what for, and when.

KMS keys, HSMs and the Encrypt and Decrypt calls

AWS KMS (Key Management Service) creates and uses cryptographic keys for you. A KMS key is a logical resource (key ID, ARN, aliases such as alias/orders, a key policy, a state) backed by key material that is generated and used only inside hardware security modules validated under FIPS 140. KMS has no operation that exports a KMS key's material in plaintext. You send data to KMS and KMS does the cryptography. (If you're unsure what encryption gives you that hashing doesn't, see hashing vs encryption.)

The default key type is a symmetric encryption key (SYMMETRIC_DEFAULT, AES-256-GCM). Its two basic calls are:

  • Encrypt: takes up to 4 KB of plaintext and returns a ciphertext blob;
  • Decrypt: takes that blob and returns the plaintext. For symmetric keys the blob records which key was used, so KeyId is optional.

The 4 KB limit is deliberate: KMS is for keys and small secrets, not files. Large data uses envelope encryption, next.

Key typeWho controls itExamples
AWS ownedThe service, invisible in your accountDefault encryption in some services
AWS managedAWS creates it per service; you can see it and its use, but not change its policyaws/s3, aws/ebs, aws/rds, aws/secretsmanager
Customer managedYou: key policy, grants, rotation, enable/disable, deletionalias/orders

Customer managed keys carry a monthly charge and are the ones to use when you need your own access rules, cross-account use or an audit story you control. Deleting one is scheduled with a waiting period of 7 to 30 days (30 by default), because once the material is gone, everything encrypted under it is unreadable.

Every KMS API call is recorded by AWS CloudTrail: the caller, the operation, the key and the time.

Keys that never leave the vault4 steps
๐Ÿฆ The vaultVisitor book0123๐ŸชAna's shop๐Ÿง‘โ€๐Ÿ’ผVault clerk๐Ÿ—๏ธAna's master key
Press play and watch it happen!

Lock your box with a small key, and let the vault lock the key

The window only takes small envelopes. But Ana's contracts fill a whole box, and walking every page to the vault would take all day. So she does something smarter.

She asks the clerk for a fresh small key. The clerk gives her two things: the small key itself, and a copy of it sealed in a tin that only her master key opens. Ana locks her box at the shop with the small key, tapes the sealed tin to the box, and throws the loose small key away.

Now the box sits in her shop, locked. Anyone who finds it sees a locked box and a sealed tin, and neither helps them. When Ana needs the contracts, she takes only the tin to the vault, the clerk unseals it and hands back the small key, and she opens the box herself. Only the tiny tin ever travels. This is called envelope encryption: the box is locked with a small key, and the small key is sealed too.

Envelope encryption with GenerateDataKey

To encrypt more than 4 KB, ask KMS for a data key. GenerateDataKey (with KeySpec=AES_256) returns:

  • Plaintext: a fresh 256-bit data key, which you use locally (for example with AES-GCM) to encrypt the data;
  • CiphertextBlob: the same data key encrypted under your KMS key.

Encrypt the data, discard the plaintext data key from memory, and store the encrypted data key next to the ciphertext (in object metadata, a file header, a column). To read, send the encrypted data key to Decrypt, get the plaintext data key back, decrypt locally and discard it again. Only the small encrypted data key travels to KMS, so data size doesn't matter, and the KMS key never leaves KMS.

1KmsClient kms = KmsClient.create();2 3GenerateDataKeyResponse dk = kms.generateDataKey(r -> r4        .keyId("alias/orders")5        .keySpec(DataKeySpec.AES_256)6        .encryptionContext(Map.of("tenant", "acme")));7 8byte[] dataKey = dk.plaintext().asByteArray();   // use with AES-GCM, then wipe9byte[] sealedKey = dk.ciphertextBlob().asByteArray(); // store next to the data

The optional encryption context is non-secret key-value data bound to the ciphertext: Decrypt fails unless the same context is supplied, and it appears in CloudTrail, which makes logs far more useful. In practice the AWS Encryption SDK implements this whole pattern for you.

AWS services do exactly this, transparently. S3 with SSE-KMS, EBS volumes and RDS storage encryption ask KMS for data keys and keep the encrypted copies with your data. You pick a key (the AWS managed one or yours) and reads and writes look unchanged. S3 bucket keys cut KMS request costs by deriving object keys from a bucket-level key instead of calling KMS per object. An RDS instance must be encrypted when it's created; to encrypt an existing one, copy a snapshot with encryption and restore it. See S3 for how SSE-KMS fits with its other encryption options.

Envelope encryption5 steps
Ana's box012๐ŸชAna's shop๐ŸฆVault clerk
Press play and watch it happen!
๐Ÿ”ง Going deeper

Key rotation. Rotation gives a KMS key new key material while the key ID, ARN and policy stay the same. KMS keeps every older version, so old ciphertexts still decrypt, and new encryptions use the newest material. It does not re-encrypt existing data. AWS managed keys rotate every year and you can't change that. For customer managed symmetric keys with KMS-generated material, automatic rotation is optional: enabled with EnableKeyRotation, every 365 days by default, with RotationPeriodInDays between 90 and 2560. Envelope encryption is why this is cheap: rotating the KMS key changes only how new data keys are sealed.

Request quotas. KMS calls count against per-account, per-Region request-rate quotas. Calling KMS once per record in a hot path can be throttled; cache or reuse data keys where the security model allows (the Encryption SDK supports this), or use S3 bucket keys.

Who may use a key, and the visitor book

Every master key's hook has a card on it, the key's own rule card, called the key policy. The clerk always reads it first. It can name people directly ("Ana may lock and unlock"), and it can say "people whose own company lists say so may use this key too". Only then does the clerk look at the list Ana's company gave her.

So if Leo's company list says he may use any key, but this key's card doesn't let company lists count, the clerk says no. The key's card always has the last word.

Sometimes Ana wants a helper, like the storage room clerk, to open her tins for her. Instead of rewriting the card, she hands the clerk a small slip: "the storage room clerk may unseal tins for my boxes, until I tear this up." Slips are quick to give and quick to take back.

Every visit, allowed or refused, goes in the visitor book. If something ever goes wrong, Ana can read exactly who used her key and when.

Key policies, IAM and grants

Every KMS key has exactly one key policy, a resource-based policy, and it is the root of access to that key: an IAM identity policy only grants KMS permissions if the key policy allows IAM policies to be used. The default key policy does this with a statement whose principal is the account (arn:aws:iam::111122223333:root), which delegates to IAM. Remove it and only the principals named in the key policy can use the key, whatever their IAM policies say. An explicit deny anywhere still wins.

Permissions are per operation: kms:Encrypt, kms:Decrypt, kms:GenerateDataKey, kms:CreateGrant, and the administrative ones (kms:PutKeyPolicy, kms:ScheduleKeyDeletion). Separate key administrators from key users. Conditions such as kms:ViaService (only when called through S3 in this Region) and kms:EncryptionContext:... narrow access further.

A grant (CreateGrant) is a lightweight, programmatic delegation: it lets a grantee principal use the key for named operations, optionally constrained to an encryption context, without editing the key policy. AWS services use grants heavily; for example, when an encrypted EBS volume attaches to an instance, Amazon EC2 creates one so it can decrypt the volume's data key. Grants are removed with RetireGrant or RevokeGrant.

CloudTrail records every KMS call, allowed or denied, with the principal, key ARN and encryption context. Because every read of encrypted data needs a Decrypt, the log doubles as a record of who read what.

Who may use a key5 steps
Visitor book0123๐ŸชAna's shop๐Ÿง‘Leo๐ŸฆVault clerk
Press play and watch it happen!

A drawer for passwords

Ana's shop also needs passwords: the code to the stockroom door, the login for her card machine. Writing them on a sticky note by the till is how passwords get stolen.

So the vault has a separate password drawer. Ana puts each password in it under a name, like "stockroom". The drawer keeps everything sealed with a vault master key. When Ana's shop needs the stockroom password, it asks the drawer by name, the drawer checks the shop is allowed, has the clerk unseal it, and reads it out.

Asking the drawer every single time someone opens the stockroom would mean a lot of walking. So the shop jots the password on a card in its pocket and asks again after an hour. That card is a copy, so it goes out of date if the password changes. Keep that in mind for the next part.

Storing and retrieving secrets with Secrets Manager

AWS Secrets Manager stores credentials, API keys and other secrets (a SecretString, often JSON, or a SecretBinary, up to 64 KB). Each secret is encrypted with a KMS key, aws/secretsmanager by default or a customer managed key (required for cross-account access), using envelope encryption. Secrets have versions, marked by staging labels: AWSCURRENT is what readers get by default.

Applications fetch a secret at run time with GetSecretValue, which needs secretsmanager:GetSecretValue (and kms:Decrypt on a customer managed key). Nothing is in code, images or environment files, access is controlled by IAM and an optional resource policy, and every read is in CloudTrail.

1SecretsManagerClient sm = SecretsManagerClient.create();2 3String json = sm.getSecretValue(r -> r.secretId("prod/orders/db"))4        .secretString(); // {"username":"orders_app","password":"..."}

Each call costs money and latency, so cache secrets client-side. AWS's Java caching library (aws-secretsmanager-caching-java, class SecretCache) refreshes cached values every hour by default; Lambda functions can use the AWS Parameters and Secrets Lambda Extension. A cache means a rotated secret is picked up late, so on an authentication failure, refresh the secret and retry once.

Deleting a secret is scheduled with a recovery window of 7 to 30 days (30 by default).

A drawer for passwords4 steps
๐ŸชAna's shop๐Ÿ—„๏ธPassword drawer๐ŸฆVault clerk๐ŸšชStockroom door
Press play and watch it happen!

Changing the password on a schedule

A password that never changes is a password someone will eventually leak. So the drawer has a caretaker who changes passwords on a timetable Ana picks, say every 30 days. That's called rotation, and the caretaker works in four careful moves:

  1. Make up a new password and put it in the drawer, marked "pending", next to the current one.
  2. Go to the stockroom door and change its lock to the new password.
  3. Try the new password on the door, to be sure it works.
  4. Move the "current" tag to the new password, and mark the old one "previous", just in case.

If anything fails before the tag moves, the shop still gets the old password, never an untested one. But if the lock was already changed, someone must fix it quickly.

For some doors the bank built and runs for her, like a stockroom it looks after, the bank sends its own caretaker and Ana doesn't have to arrange anything.

Automatic rotation with Lambda, and managed rotation

Rotation replaces a secret's value on a schedule (rate(30 days) or a cron() expression, as often as every four hours) or on demand with RotateSecret. For most secrets, a rotation Lambda function does the work in four steps, each called with the same version token:

  1. createSecret: generate a new value and store it as a new version labelled AWSPENDING;
  2. setSecret: change the credential in the database or service to the pending value;
  3. testSecret: log in with the pending value;
  4. finishSecret: move AWSCURRENT to the new version; the old one gets AWSPREVIOUS.

Until step 4 succeeds, readers still get the old value, never an untested one. If the failure comes after setSecret, that old value may already be invalid, so alert on rotation failures. AWS provides template functions for common databases, with two strategies: single user (change one user's password; brief failures are possible for connections opened mid-rotation) and alternating users (two users take turns, so the current credentials always work).

Managed rotation needs no Lambda: services such as RDS can manage the master user password in Secrets Manager (ManageMasterUserPassword) and rotate it themselves, every seven days by default.

Rotation and caching interact: clients holding a cached old value keep working only while the old credential is still valid. Alternating users, a cache TTL shorter than the overlap, or refresh-on-auth-failure handle it.

Rotating a secret6 steps
Password drawer012๐ŸชAna's shop๐ŸงนCaretaker๐ŸšชStockroom door
Press play and watch it happen!

The shop picks up its passwords at opening time

When Ana's shop opens each morning, before serving anyone, it collects the passwords it needs from the drawer and keeps them handy for the day. The code that runs the shop never has a password written in it.

There's also a cheaper option by the counter: a row of locked mailboxes. They're sealed with the same vault keys and are great for settings and small secrets, but nobody changes what's inside on a schedule. Ana uses the drawer for passwords that should change, and a mailbox for the rest.

Spring Cloud AWS, and Parameter Store SecureString

With Spring Cloud AWS (spring-cloud-aws-starter-secrets-manager), secrets load into the Spring Environment at start-up through Spring Boot's config import:

1spring.config.import=aws-secretsmanager:prod/orders/db?prefix=db.2spring.datasource.username=${db.username}3spring.datasource.password=${db.password}

For a JSON secret, every top-level key becomes a property (?prefix=db. turns username into db.username); a plain-text secret is available under its name (the last path segment, so /secrets/prod/jdbc-url is ${jdbc-url}). A missing secret fails start-up unless you write optional:aws-secretsmanager:.... Separate several secrets with ;. Credentials come from the default provider chain, so the app's IAM role needs secretsmanager:GetSecretValue. Values are read once at start-up, so after a rotation the app needs a restart, Spring Cloud AWS's reload support, or a connection pool that re-reads the secret on authentication failure.

SSM Parameter Store SecureString parameters are also encrypted with KMS (aws/ssm or your key) and read with GetParameter and WithDecryption=true (Spring Cloud AWS: aws-parameterstore:). Standard parameters are free and hold up to 4 KB, advanced ones 8 KB. Parameter Store has no built-in rotation, so:

Secrets ManagerParameter Store SecureString
RotationBuilt in (Lambda or managed)None
Size64 KB4 KB standard, 8 KB advanced
CostPer secret per month, plus API callsStandard tier free
Best forDatabase and API credentialsConfig and static secrets
Spring Boot loads its secrets at start-up5 steps
๐ŸชAna's shop๐Ÿ—„๏ธPassword drawer๐Ÿ“ฌCounter mailbox๐ŸšชStockroom door
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about AWS KMS and Secrets Manager, told the same way as the story.
  1. A thief breaks into Ana's shop and steals a locked box with its sealed tin taped on. What can the thief read?
  2. Why doesn't Ana just hand all her contracts to the vault clerk to lock, page by page?
  3. Leo's company list says he may use any vault key. The card on Ana's key names only Ana and doesn't let company lists count. What happens when Leo asks?
  4. The caretaker has put a new password in the drawer and changed the lock, but the test try fails. What does the shop get when it asks for the password?
  5. Ana keeps some secrets in a counter mailbox instead of the password drawer. Which secret belongs in the drawer?
Answer every question to check.Passing marks AWS KMS and Secrets Manager as done.
Got the hang of AWS KMS and Secrets Manager? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ›ฐ๏ธ AWS in productionStep 7 of 7

โ† Previous on the path๐Ÿš Amazon CloudWatchLast step ๐ŸŽ‰Back to the path