How to encrypt and decrypt using AWS KMS
The article shows how to use AWS KMS to encrypt and decrypt data.
Published Jan 5, 2025
In the last post, I provided an overview of AWS KMS. Here, I'll walk you through the process of using it.
There are two apporaches to use AWS KMS. The one is AWS CLI and OpenSSL, the other is AWS Encryption SDK. Today, I'll introduce how to use AWS KMS using AWS CLI and OpenSSL.
OpenSSL is an open-source software library that provides essential cryptographic tools and implements the SSL/TLS protocols for secure communication. It supports a wide range of cryptographic algorithms, including encryption, decryption, digital signatures, and hash functions. OpenSSL is widely used to secure data transmission over the internet, manage digital certificates, and perform various cryptographic operations through its command-line tools. You can click here if you would like to learn more. We can use OpenSSL to communicate with AWS KMS over AWS CLI.
There are five steps to teach you how to AWS KMS using OpenSSL and AWS CLI.
First of all, we should check our environment is well prepared.
- Make sure we have installed AWS CLI. If not, please click here to install it first.
- Make sure we have installed OpenSSL. If not, please click here to download it and then install. Also, you can google how to install OpenSSL.
Now, let's move on the next step!
We can use AWS KMS in our AWS account as follow:
Now, we have created a CMK
test
.We can use AWS CLI and OpenSSL to generate data key.
Response as below
It returns
Plaintext
and CiphertextBlob
, which are base64 encoded. So we need to decode and save them into dataKey and encrypted-datakey files.- decode dataKey
- decode encrypted-dataKey
We will use thoes two files below.
Firstly, we need to create our sensitive data into
password.txt
.Now, we use
dataKey
file to encrypt the sensitive data in password.txt
. The output encrypted data is in encrypted-password.txt
.We should delete
dataKey
after encrypting the data.How do we decrypt the encrypted data? Firstly, we need to use
encrypted-datakey
to get Plaintext
in KMS.The output is below
Now we can use this
Plaintext
to decrypt our data. But first, we should do base64 decode and save it as dataKey again.Finally, we can decrypt our encrypted data
encrypted-password.txt
with the dataKey
. The decrypted sensitive data is output to decrypted-password.txt
.Now, the
decrypted-password.txt
is the original sentivite data in password.txt
.