How to encrypt and decrypt using AWS KMS
The article shows how to use AWS KMS to encrypt and decrypt data.
- Make sure we have installed AWS CLI. If not, please click here to install it first.
1
2
aws --version
aws-cli/2.15.6 Python/3.11.6 Darwin/23.6.0 exe/x86_64 prompt/off
- 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.
1
2
openssl --version
OpenSSL 3.4.0 22 Oct 2024 (Library: OpenSSL 3.4.0 22 Oct 2024)
test
.1
aws kms generate-data-key --key-id alias/test --key-spec AES_256 --region us-east-1
1
2
3
4
5
{
"CiphertextBlob": "AQIDAHi71gCapMjMwnPHLHPcI0frWP6y0RXUSPXAF/9wSxFhOgGiXwg7BWsllukeqLQf/EApAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMz5xgmiIe/LnLEvvcAgEQgDuIKYN4tsL48jrC9k5BiZDslFeXh31cXcZxryCQlER9YUAQRDsFs7abo5rgvnT7uhGBp2Grq9nqXeiICg==",
"Plaintext": "00oP+1SBZc73ileO1VRYLpE3aqIQUQbOPrmY4TSBYQ4=",
"KeyId": "arn:aws:kms:us-east-1:157854716818:key/4d1cdb9b-9a7e-4072-a01c-9d00b9fb7dec"
}
Plaintext
and CiphertextBlob
, which are base64 encoded. So we need to decode and save them into dataKey and encrypted-datakey files.- decode dataKey
1
echo "00oP+1SBZc73ileO1VRYLpE3aqIQUQbOPrmY4TSBYQ4=" | base64 --decode > dataKey
- decode encrypted-dataKey
1
echo "AQIDAHi71gCapMjMwnPHLHPcI0frWP6y0RXUSPXAF/9wSxFhOgGiXwg7BWsllukeqLQf/EApAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMz5xgmiIe/LnLEvvcAgEQgDuIKYN4tsL48jrC9k5BiZDslFeXh31cXcZxryCQlER9YUAQRDsFs7abo5rgvnT7uhGBp2Grq9nqXeiICg==" | base64 --decode > encrypted-datakey
password.txt
.1
echo "This is my password" > password.txt
dataKey
file to encrypt the sensitive data in password.txt
. The output encrypted data is in encrypted-password.txt
.1
openssl enc -in ./password.txt -out ./encrypted-password.txt -e -aes256 -k fileb://./dataKey
dataKey
after encrypting the data.1
rm dataKey
encrypted-datakey
to get Plaintext
in KMS.1
aws kms decrypt --ciphertext-blob fileb://./encrypted-datakey --region us-east-1
1
2
3
4
5
{
"KeyId": "arn:aws:kms:us-east-1:157854716818:key/4d1cdb9b-9a7e-4072-a01c-9d00b9fb7dec",
"Plaintext": "00oP+1SBZc73ileO1VRYLpE3aqIQUQbOPrmY4TSBYQ4=",
"EncryptionAlgorithm": "SYMMETRIC_DEFAULT"
}
Plaintext
to decrypt our data. But first, we should do base64 decode and save it as dataKey again.1
echo "00oP+1SBZc73ileO1VRYLpE3aqIQUQbOPrmY4TSBYQ4=" | base64 --decode > dataKey
encrypted-password.txt
with the dataKey
. The decrypted sensitive data is output to decrypted-password.txt
.1
openssl enc -in ./encrypted-password.txt -out ./decrypted-password.txt -d -aes256 -k fileb://./dataKey
decrypted-password.txt
is the original sentivite data in password.txt
.1
2
cat decrypted-password.txt
This is my password