Creating an AWS KMS Key and Using AWS CLI to Encrypt and Decrypt Files

By Łukasz Kallas
Picture of the author
Published on
aws image

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

  1. 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.
  2. Prepare AWS CloudShell:

    • Open AWS CloudShell from the AWS Management Console.
    • Ensure that AWS CLI is configured with the necessary permissions to access KMS.
  3. 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
      
  4. 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.

Stay Tuned

Want to learn?
The best articles, links and news related to software development delivered once a week to your inbox.