This tutorial shows you how to create a customer managed KMS key, assign it an alias, encrypt and decrypt data, and generate a data key for client-side encryption.
- AWS CLI configured with credentials and a default region
- Permissions for
kms:CreateKey,kms:CreateAlias,kms:DescribeKey,kms:Encrypt,kms:Decrypt,kms:GenerateDataKey,kms:ListAliases,kms:ScheduleKeyDeletion,kms:DeleteAlias
KEY_ID=$(aws kms create-key --description "Tutorial key" \
--query 'KeyMetadata.KeyId' --output text)
echo "Key ID: $KEY_ID"KMS returns the key metadata including the key ID, ARN, and state. The key is enabled immediately.
An alias is a friendly name for your key. Alias names must start with alias/.
aws kms create-alias --alias-name "alias/tutorial-key" --target-key-id "$KEY_ID"aws kms describe-key --key-id "$KEY_ID" \
--query 'KeyMetadata.{KeyId:KeyId,State:KeyState,Created:CreationDate,Description:Description}' \
--output tableWrite plaintext to a file and encrypt it using fileb:// to pass raw bytes:
echo "Hello from the KMS tutorial" > plaintext.txt
aws kms encrypt --key-id "$KEY_ID" \
--plaintext "fileb://plaintext.txt" \
--output text --query 'CiphertextBlob' > ciphertext.b64The fileb:// prefix tells the CLI to read the file as raw binary. The output is base64-encoded ciphertext.
Decode the base64 ciphertext to binary, then decrypt:
base64 --decode ciphertext.b64 > ciphertext.bin
aws kms decrypt --ciphertext-blob "fileb://ciphertext.bin" \
--output text --query 'Plaintext' | base64 --decodeKMS identifies the correct key from metadata embedded in the ciphertext.
A data key lets you encrypt data locally. KMS returns both a plaintext key (for immediate use) and an encrypted copy (to store alongside your data).
aws kms generate-data-key --key-id "$KEY_ID" --key-spec AES_256 \
--query '{KeyId:KeyId}' --output tableaws kms list-aliases \
--query 'Aliases[?starts_with(AliasName, `alias/tutorial`)].{Alias:AliasName,KeyId:TargetKeyId}' \
--output tableSchedule the key for deletion (minimum 7-day waiting period) and delete the alias:
aws kms schedule-key-deletion --key-id "$KEY_ID" --pending-window-in-days 7
aws kms delete-alias --alias-name "alias/tutorial-key"The key incurs $1/month until the scheduled deletion completes. The script automates all steps including cleanup:
bash aws-kms-gs.sh