Encrypt and Decrypt Data with KMS and Data Keys
Learn how to encrypt and decrypt data with KMS keys and with Data Keys
Symmetric Encryption/Decryption
Encrypting Plaintext
You can take plaintext (regular data like what you’re reading right now) and pass it through an encryption algorithm with a KMS Key in order to get ciphertext (encrypted data) back, all without leaving the Key Management Service (KMS) when dealing with smaller data.
By default, when you create a new AWS KMS key, you receive a symmetric encryption KMS key. Symmetric encryption uses the same key to both encrypt and decrypt data.
KMS symmetric keys allow for data encryption up to 4096 bytes in size. The data is sent to KMS, it gets encrypted, and then it gets sent back to the sender which could be a service, application, or yourself. In this case, the encryption key never leaves KMS. If you need to encrypt larger data, see →
aws kms encrypt --key-id alias/lab-key --profile cybrkmslab \
--plaintext fileb://plaintext_favorite_dog.txt \
--output text --query CiphertextBlob | \
base64 --decode > encrypted_favorite_dog.txtaws kms decrypt --key-id alias/lab-key --profile cybrkmslab \
--ciphertext-blob fileb://encrypted_favorite_dog.txt \
--output text --query Plaintext | \
base64 --decode > decrypted_favorite_dog.txtEncrypting data greater than 4096 bytes in size
When data larger than 4096 bytes needs to be encrypted, KMS can generate a data key. This data key leaves KMS and is sent back to the sender. The sender is then responsible for managing the security of the key.
The data key that you receive is encrypted with a KMS key and you use the decrypted (plaintext) data key to encrypt data. You can then immediately discard it after use since you can retrieve it at a later time for decryption purposes.
aws kms generate-data-key \
--key-id alias/lab-key \
--key-spec AES_256 --profile kmslabOutputs:
• CiphertextBlob → encrypted_text
• Plaintext → plaintext_keyKEY_HEX=$(xxd -p -c 256 plaintext_key)
IV=$(openssl rand -hex 16) && echo $IV > iv.txtopenssl enc -aes-256-cbc \
-K $KEY_HEX -iv $IV \
-in file.txt -out encrypted_file.txt
rm plaintext_key- or -
Using the AWS Encryption SDK
aws-encryption-cli --encrypt \
--input plaintext_sdk_example.txt \
--output encrypted_sdk_example.txt \
--wrapping-keys key=key-arn-value-here profile=cybrkmslab \
--commitment-policy require-encrypt-require-decrypt \
--metadata-output metadataaws-encryption-cli --decrypt \
--input encrypted_sdk_example.txt \
--output decrypted_sdk_example.txt \
--wrapping-keys key=key-arn-value-here profile=kmslab \
--metadata-output metadata --max-encrypted-data-keys 1 \
--buffer --commitment-policy require-encrypt-require-decrypt🧪 Learn KMS By Doing
Use this cheat sheet with AI
Copy a ready-to-use prompt into your preferred AI assistant.
Cybr