Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

AWS CLI KMS Commands: Create a Key, Encrypt and Decrypt

We lock data with keys AWS guards for us: create a key and alias, encrypt and decrypt, use data keys for big files, rotate, grant and delete safely.

In this chapter

  • Create a key and alias
  • Encrypt and decrypt
  • Envelope encryption
  • Rotation and policies
  • Grants and deletion

1. The big picture: the master key with the watchman

In a society the watchman keeps the master key and writes down who borrowed it. KMS keeps your master key inside hardware, never hands it out, and CloudTrail records every use.

Commands are in aws kms: create-key, create-alias, encrypt, decrypt, generate-data-key, enable-key-rotation, schedule-key-deletion.

Encryption workflowcreate-keycreate-alias alias/cli-appencrypt (up to 4 KB)generate-data-key for big datadecrypt
The master key never leaves KMS.

2. Create a key and alias

Services like S3, EBS and RDS need a key you control and can audit.

create-key makes a symmetric customer managed key. An alias is a friendly name you can move to another key.

  1. Create and alias.
K=$(aws kms create-key --description "cli app key" --query KeyMetadata.KeyId --output text)
aws kms create-alias --alias-name alias/cli-app --target-key-id $K
aws kms list-aliases --query "Aliases[?AliasName=='alias/cli-app'].TargetKeyId" --output text

Expected output:

1234abcd-12ab-34cd-56ef-1234567890ab

3. Encrypt and decrypt

For the short-message portion, write harmless text into the lab’s plain.txt. The key alias alias/cli-app is a friendly reference to the KMS key. The CLI fileb:// argument reads the file bytes. The encrypt response exposes ciphertext bytes in a base64 representation, which permits binary data to travel in JSON or text. Decoding that output into secret.bin recovers encrypted bytes, not readable text.

Use the existing decrypt procedure to ask KMS to open those ciphertext bytes. Decode the returned plaintext field into the restored file and compare it with the disposable original. If you only run a base64 decoder on the ciphertext, the result remains encrypted. If KMS rejects the request, distinguish key selection, permissions and any matching context. The envelope section extends the same key-control idea to a separately encrypted file.

You want to store a small secret, like a token, safely in a file or database.

encrypt takes up to 4 KB and returns base64 ciphertext. decrypt finds the key from the ciphertext itself.

  1. Encrypt a file.
echo "hello pune" > plain.txt
aws kms encrypt --key-id alias/cli-app --plaintext fileb://plain.txt --query CiphertextBlob --output text | base64 -d > secret.bin
ls -l secret.bin

Expected output:

-rw-r--r-- 1 you you 184 Oct 24 11:40 secret.bin
  1. Decrypt it.
aws kms decrypt --ciphertext-blob fileb://secret.bin --query Plaintext --output text | base64 -d

Expected output:

hello pune
  1. Use an encryption context.
aws kms encrypt --key-id alias/cli-app --plaintext fileb://plain.txt --encryption-context app=shop --query KeyId --output text

Expected output:

arn:aws:kms:ap-south-1:111122223333:key/1234abcd-...

4. Envelope encryption with data keys

With envelope encryption, a data key encrypts the application data locally. KMS protects that data key with a KMS key. GenerateDataKey can return a usable plaintext data key and an encrypted copy. Use the plaintext data key for the encryption library, then discard it. Store the encrypted copy alongside the encrypted file, with whatever metadata your chosen library needs to open it.

During readback, the authorized application asks KMS to decrypt the encrypted data key. It uses the resulting key locally to open the file. If your lab ties a KMS operation to an encryption context, supply the same context on decrypt. Try a small disposable text round trip and compare the decrypted content with the original. The encrypted data key by itself does not contain the file.

A 2 GB backup is too big for KMS encrypt, and sending it over the network is slow.

generate-data-key returns a plaintext key (use and forget) and the same key encrypted (store next to the data). To read, decrypt the small key, then the data locally.

  1. Get a data key.
aws kms generate-data-key --key-id alias/cli-app --key-spec AES_256 --query "[Plaintext,CiphertextBlob]" --output text > dk.txt
cut -f1 dk.txt | base64 -d > dk.bin; cut -f2 dk.txt | base64 -d > dk.enc

Expected output:

(two files: dk.bin 32 bytes, dk.enc)
  1. Encrypt the big file locally, then drop the plain key.
openssl enc -aes-256-cbc -pbkdf2 -in backup.tar -out backup.tar.enc -pass file:dk.bin
shred -u dk.bin dk.txt
ls backup.tar.enc dk.enc

Expected output:

backup.tar.enc  dk.enc

5. Rotation, grants and deletion

Keys should change yearly; a service may need temporary use; old keys must go carefully.

enable-key-rotation rotates key material yearly; old data still decrypts. create-grant gives temporary use. schedule-key-deletion waits 7–30 days and can be cancelled.

  1. Turn on rotation.
aws kms enable-key-rotation --key-id $K
aws kms get-key-rotation-status --key-id $K --query KeyRotationEnabled

Expected output:

true
  1. Grant a role decrypt.
aws kms create-grant --key-id $K --grantee-principal arn:aws:iam::111122223333:role/cli-lambda-role --operations Decrypt --query GrantId --output text

Expected output:

0c237476b39f8bc44e45212e08498fbe3151305030726c0590dd8d3824f9
  1. Disable first, if unsure.
aws kms disable-key --key-id $K
aws kms describe-key --key-id $K --query KeyMetadata.KeyState --output text

Expected output:

Disabled

6. Same action in Python, Node.js, Java, Go, .NET and PHP

Scripts start in the CLI. Apps call the same API through an SDK. Knowing both helps you move a tested command into real code.

Low-level CLI commands expose service operations. A high-level command or an automatically paginated list can make multiple requests. For example, aws kms encrypt --key-id alias/cli-app --plaintext fileb://plain.txt maps to the Encrypt API.

Same action (Encrypt) from code. Set the intended profile and Region for the SDK. Provider support and precedence can differ by SDK, and an explicit client setting can override defaults.

StackCode
Python (boto3)boto3.client("kms").encrypt(KeyId="alias/cli-app",Plaintext=b"hello")["CiphertextBlob"]
Node.js (v3)await kms.send(new EncryptCommand({KeyId:"alias/cli-app",Plaintext:Buffer.from("hello")}));
Java (v2)kms.encrypt(r -> r.keyId("alias/cli-app").plaintext(SdkBytes.fromUtf8String("hello")));
Go (v2)c.Encrypt(ctx, &kms.EncryptInput{KeyId: aws.String("alias/cli-app"), Plaintext: []byte("hello")})
.NETawait kms.EncryptAsync(new EncryptRequest{KeyId="alias/cli-app",Plaintext=new MemoryStream(Encoding.UTF8.GetBytes("hello"))});
PHP$kms->encrypt(["KeyId"=>"alias/cli-app","Plaintext"=>"hello"]);

7. Clean up so nothing keeps costing

Lab resources left running cost money and can be a security risk.

Delete in reverse order: children first, then parents.

  1. Delete the alias.
aws kms delete-alias --alias-name alias/cli-app

Expected output:

(no output means success)
  1. Schedule key deletion (minimum 7 days).
aws kms schedule-key-deletion --key-id $K --pending-window-in-days 7 --query KeyState --output text

Expected output:

PendingDeletion
  1. Changed your mind?
aws kms cancel-key-deletion --key-id $K --query KeyId --output text

Expected output:

1234abcd-12ab-34cd-56ef-1234567890ab

Ravindra Bagale's Tip

Deleting a KMS key makes every piece of data encrypted with it unreadable forever. Disable the key first and watch CloudTrail for failed decrypts before scheduling deletion.

8. Interview questions and answers

Q. What is envelope encryption?

Encrypt data with a data key, and encrypt that data key with a KMS key.

Q. Why does decrypt not need --key-id?

For symmetric keys the key id is inside the ciphertext.

Q. AWS managed vs customer managed key?

AWS managed (aws/s3) is automatic; customer managed gives you policy, rotation and deletion control.

Q. Encrypt size limit?

4 KB of plaintext per encrypt call.

Q. What is an encryption context?

Extra key-value data bound to the ciphertext; the same context is required to decrypt and is logged.

Try at home

  1. Encrypt a file with an encryption context and try decrypting without it.
  2. Do envelope encryption on a 10 MB file and restore it.

In short

  1. create-key + alias.
  2. encrypt ≤ 4 KB.
  3. Data keys for big data.
  4. Enable rotation.
  5. Disable before delete.

Record the key and encryption context for a round trip

Encrypt a lab payload using a disposable authorized key. Decrypt with the same encryption context where used. Compare plaintext locally; do not put secrets in the context or logs. Scheduling deletion affects future decryptability and should be done only for lab keys with verified usage.

Interview check Why does decrypt fail even with the correct key ID?

The original encryption context must be supplied exactly for operations that used it. Key state, Region, permissions and the correct ciphertext format also matter.

Reference documentation

Practise this chapter

Interview questions and answers

Walk through what you would store and what you would discard in envelope encryption.

I would use the plaintext data key only while encrypting and discard it afterwards. I would store the encrypted file, its encrypted data key and required metadata. An authorized reader calls KMS to open the encrypted data key, then uses it locally to decrypt the file.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What encrypts the application file in the envelope example?

Answer and explanation

C. The plaintext data key used locally by the encryption library

The local library uses usable data-key material. KMS protects the key material separately.

2. Which data key copy is stored alongside the encrypted file?

Answer and explanation

A. The encrypted copy

The encrypted copy can later be decrypted by an authorized KMS call. Persisting plaintext would defeat separation.

3. Which look-up step is needed before opening the file?

Answer and explanation

B. Decrypt the saved encrypted data key with the appropriate KMS operation

The same data key is needed to decrypt the corresponding file, with matching context when required.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Ahmednagar Sugar Co-op is a sugar co-operative business in Ahilyanagar. Balasaheb Pawar looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 10

Easy Create a KMS key

A customer managed key lets you control who can encrypt and decrypt.

Create a KMS key with description "nagarsugar data key".

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Turn on yearly key rotation

Automatic rotation changes the key material without breaking old data.

Enable automatic rotation for key 1234abcd-12ab-34cd-56ef-1234567890ab.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy How many addresses in a /16?

Picking a VPC size needs this count.

Ahmednagar Sugar Co-op plans the VPC 10.26.0.0/16. How many IP addresses does it hold in total?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Port for SSH

Security group rules need the right port.

Which TCP port must the security group open for SSH?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Give the key a friendly alias

Aliases are easier to read than key IDs and can be moved to a new key.

Create alias alias/nagarsugar-data for key 1234abcd-12ab-34cd-56ef-1234567890ab.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Decrypt a blob

The ciphertext remembers which key made it, so decrypt needs only the blob.

Decrypt the ciphertext stored in secret.enc.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Encrypt a small file

KMS Encrypt works for data up to 4 KB, like a password or token.

Encrypt secret.txt with key alias/nagarsugar-data.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Use a key, not manage it

Apps need Encrypt/Decrypt; only admins should change or delete keys.

Allow kms:Encrypt, kms:Decrypt, kms:GenerateDataKey on arn:aws:kms:ap-south-1:131959625285:key/1234abcd-12ab-34cd-56ef-1234567890ab only.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Generate a data key

Envelope encryption: KMS gives a data key; you encrypt big files locally with it.

Generate an AES_256 data key under alias/nagarsugar-data.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Default encryption with KMS

Default encryption makes sure every new object is encrypted, even if the uploader forgets.

Apply the encryption settings in enc.json to bucket nagarsugar-hr-docs.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

KMS encrypt. The watchman never hands out the master key. create-key and alias. encrypt up to 4 KB. decrypt finds the key itself.
Revision card: KMS encrypt · Download PNG · Open card page
KMS data keys. Big files need envelope encryption. generate-data-key: plain + encrypted. Encrypt locally, shred the plain key. Disable before schedule-key-deletion.
Revision card: KMS data keys · Download PNG · Open card page
kms encrypt vs Data key. Up to 4 KB. / Any size, local.
Comparison: kms encrypt vs Data key · Download PNG · Open card page
What is envelope encryption?. Data key encrypts data. KMS key encrypts the data key. Store the encrypted key with the data.
Interview card: What is envelope encryption? · Download PNG · Open card page

More cards: Ravi Sir's Cards.