Now that you have created a KMS key, you can use this key to encrypt and decrypt data.
The following example demonstrates encrypting a simple plain text value using the AWS CLI:
> aws kms encrypt --key-id alias/secrets-key --plaintext "Hello World"
{
"CiphertextBlob": "AQICAHifCoHWAYb859mOk+pmJ7WgRbhk58UL9mhuMIcVAKJ18gHN1/SRRhwQVoVJvDS6i7MoAAAAaTBnBgkqhkiG9w0BBwagWjBYAgEAMFMGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMYm4au5zNZG9wa5ceAgEQgCZdADZyWKTcwDfTpw60kUI8aIAtrECRyW+/tu58bYrMaZFlwVYmdA==",
"KeyId": "arn:aws:kms:us-east-1:385605022855:key/ee08c380-153c-4f31-bf72-9133b41472ad"
}
In the preceding example, note that you must specify the KMS key ID or alias using the --key-id flag, and whenever you use a KMS key alias, you always prefix the alias with alias/<alias-name>. The encrypted data is returned as a Base64-encoded binary blob in the CiphertextBlob property, which conveniently also encodes the key ID of the encrypted KMS key into the encrypted data, meaning the KMS service can decrypt the ciphertext blob without requiring you to explicitly specific the encrypting KMS key ID:
> ciphertext=$(aws kms encrypt --key-id alias/secrets-key --plaintext "Hello World" --query CiphertextBlob --output text)
> aws kms decrypt --ciphertext-blob fileb://<(echo $ciphertext | base64 --decode)
{
"KeyId": "arn:aws:kms:us-east-1:385605022855:key/ee08c380-153c-4f31-bf72-9133b41472ad",
"Plaintext": "SGVsbG8gV29ybGQ="
}
In the preceding example, you encrypt some data, this time using the AWS CLI query and text output options to capture the CiphertextBlob property value in a bash variable called ciphertext. You then use the aws kms decrypt command to pass in the cipher text as a blob file using bash process substitution to feed the Base64 decoded value of the cipher text into the binary file URI indicator (fileb://). Notice that the returned Plaintext value is not the Hello World value that you originally encrypted—this is because the Plaintext value is in a Base64 encoded format, and the following example takes the aws kms decrypt command a step further to return the original plaintext value:
> aws kms decrypt --ciphertext-blob fileb://<(echo $ciphertext | base64 --decode) \
--query Plaintext --output text | base64 --decode
Hello World