DEV Community

gurpreet kaur
gurpreet kaur

Posted on

๐Ÿ” Encrypting and Decrypting Files Using AWS KMS and Data Keys

A Practical Guide to Using KMS Keys, Data Keys, and Envelope Encryption in AWS

In todayโ€™s cloud-first world, security is paramount โ€” especially when handling sensitive data. AWS Key Management Service (KMS) provides a secure and scalable way to create and manage cryptographic keys and control their usage across a wide range of AWS services and applications.

In this blog, weโ€™ll walk through a step-by-step process to encrypt and decrypt files using AWS KMS keys and generated data keys, covering both symmetric encryption and envelope encryption scenarios.

๐Ÿ“Œ Step 1: Create an EC2 Instance with IAM Role
Launch an EC2 instance and attach an IAM role that allows it to communicate with other AWS services securely.

๐Ÿ“Œ Step 2: Attach IAM Policy to EC2 Role
Add the following IAM policy to allow access to EC2, KMS, and S3:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "ec2:DescribeInstances",
        "kms:*",
        "s3:GetObject",
        "s3:ListBucket",
        "s3:PutObject"
      ],
      "Resource": "*",
      "Effect": "Allow"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ Note: IAM policies define what actions identities (like roles or users) are allowed to perform on resources.

๐Ÿ“Œ Step 3: Create a Symmetric KMS Key
In the AWS KMS console, create a symmetric key in a specific region.
Symmetric keys use the same key for both encryption and decryption. These 256-bit keys never leave AWS unencrypted.

๐Ÿ” Key Concepts:
Symmetric Key: Same key for encrypt/decrypt.
Asymmetric Key: Public-private key pair for encryption or signing.
Key Rotation: Ensure it is enabled for better key lifecycle security.

๐Ÿ“Œ Step 4: Review the Automatically Generated Key Policy
When assigning Key Administrators and Key Users, AWS automatically generates a policy like this:

{
  "Sid": "Allow use of the key",
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::<account-id>:role/YourRole"
  },
  "Action": [
    "kms:Encrypt",
    "kms:Decrypt",
    "kms:GenerateDataKey*"
  ],
  "Resource": "*"
}
Enter fullscreen mode Exit fullscreen mode

Key policy governs access control to KMS keys.

๐Ÿ“Œ Step 5: Connect to EC2 Using Session Manager
Use AWS Session Manager to connect securely without exposing ports.

sudo su ec2-user
cd ../../home/ec2-user
echo "This is my Secret Text to encrypt." > samplesecret.txt
cat samplesecret.txt
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Generate a Data Key Using AWS KMS
Run the command:

aws kms generate-data-key \
  --key-id alias/myKMSKey \
  --key-spec AES_256 \
  --encryption-context project=practice \
  --region us-east-1
Enter fullscreen mode Exit fullscreen mode

This returns:

  • A plaintext data key (for encryption)
  • A ciphertext blob (encrypted data key, safe to store)

Save both to files:

echo '<PlaintextKey>' | base64 --decode > datakeyPlainText.txt
echo '<CiphertextBlob>' | base64 --decode > datakeyEncrypted.txt
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Encrypt a File Using the Data Key

openssl enc -e -aes256 -in samplesecret.txt -out encryptedSecret.txt -k fileb://datakeyPlainText.txt
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” View encrypted data:

more encryptedSecret.txt
Enter fullscreen mode Exit fullscreen mode

๐Ÿงน Remove plaintext key for security:

rm datakeyPlainText.txt

Enter fullscreen mode Exit fullscreen mode

๐Ÿ”“_ Decrypt the File_
First, decrypt the data key:

aws kms decrypt \
  --encryption-context project=practice \
  --ciphertext-blob fileb://datakeyEncrypted.txt \
  --region us-east-1
Enter fullscreen mode Exit fullscreen mode

Then decode and use it:

echo '<DecryptedPlaintextKey>' | base64 --decode > datakeyPlainText.txt
openssl enc -d -aes256 -in encryptedSecret.txt -k fileb://datakeyPlainText.txt
Enter fullscreen mode Exit fullscreen mode

๐ŸŽ‰ You should now see the original text โ€” decryption successful!

๐Ÿ› ๏ธ Encrypting Without Generating Data Keys (Direct KMS Encryption)
Create a new file:

echo "New secret file: encrypt without using a data key." > NewSecretFile.txt
Enter fullscreen mode Exit fullscreen mode

Encrypt it directly using your KMS key:

aws kms encrypt \
  --key-id alias/myKMSKey \
  --plaintext fileb://NewSecretFile.txt \
  --encryption-context project=practice \
  --output text \
  --query CiphertextBlob \
  --region=us-east-1 | base64 --decode > NewSecretsEncryptedFile.txt
Enter fullscreen mode Exit fullscreen mode

Decrypt it with:

aws kms decrypt \
  --ciphertext-blob fileb://NewSecretsEncryptedFile.txt \
  --encryption-context project=practice \
  --output text \
  --query Plaintext \
  --region=us-east-1 | base64 --decode > NewSecretsDecryptedFile.txt
Enter fullscreen mode Exit fullscreen mode

Verify:

cat NewSecretsDecryptedFile.txt
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ Important Notes on AWS KMS

  • AWS KMS is optimized for small data (<4KB).
  • Use Envelope Encryption: Encrypt large data with a data key, and encrypt the data key with KMS. -Always delete plaintext keys from memory after use.
  • KMS does not store or manage your data keys โ€” you manage them outside using tools like OpenSSL or AWS Encryption SDK.

๐Ÿ” Final Thoughts
Using AWS KMS with data keys allows you to build highly secure, scalable encryption workflows. Whether youโ€™re protecting secrets, encrypting files, or automating secure data flows, mastering KMS is a crucial cloud skill.

Top comments (0)