Creating an AWS KMS Key and Using AWS CLI to Encrypt and Decrypt Files
By Łukasz Kallas
- Published on
Sharing
Amazon Key Management Service (KMS) is a managed service that makes it easy to create and control the encryption keys used to encrypt your data. In this guide, we'll walk through creating a KMS key using the AWS Management Console and then using AWS CLI in CloudShell to encrypt and decrypt a text file.
Steps to Create an AWS KMS Key and Use AWS CLI
Create a KMS Key:
- Navigate to KMS (Key Management Service) in the AWS Management Console.
- Click Create key.
- Choose Symmetric for the key type, which is suitable for most encryption and decryption tasks.
- Provide a name and description for your key.
- Configure key administrators and users by selecting appropriate IAM roles and users.
- Review and click Create key to complete the process.
Prepare AWS CloudShell:
- Open AWS CloudShell from the AWS Management Console.
- Ensure that AWS CLI is configured with the necessary permissions to access KMS.
Encrypt a Text File:
- Create a text file to encrypt:
echo "Hello, this is a secret message" > secret.txt
- Use the AWS CLI to encrypt the file with your KMS key:
aws kms encrypt --key-id alias/your-key-alias --plaintext fileb://secret.txt --output text --query CiphertextBlob > encrypted.txt
- Create a text file to encrypt:
Decrypt the Text File:
- Use the AWS CLI to decrypt the file:
aws kms decrypt --ciphertext-blob fileb://<(base64 -d encrypted.txt) --output text --query Plaintext | base64 --decode > decrypted.txt
- Verify the contents of the decrypted file:
cat decrypted.txt
The decrypted file should contain the original message, confirming that the encryption and decryption process was successful.
- Use the AWS CLI to decrypt the file: