AWS KMS is a managed service for cryptographic functions in AWS. This service allows you to offload the tough job of key lifecycle management to Amazon.

These snippets will allow you to perform basic cryptographic functions - encypt, decrypt, and rewrap. It is assumed you already have a KMS key provisioned, and you have a IAM user with permissions to perform the relevant operations.

Encrypt the Contents of a File

This command encrypts the contents of contents.txt and saves the encrypted version in contents.asc.

# This example uses a key alias, but this can also be the ARN.
KMS_KEY=alias/my-kms-key
UNENCRYPTED_FILE=contents.txt
ENCRYPTED_FILE=contents.asc

aws kms encrypt \
  --key-id ${KMS_KEY} \
  --plaintext fileb://${UNENCRYPTED_FILE} \
  --output text \
  --query CiphertextBlob > ${ENCRYPTED_FILE}

Decrypt the Contents of an Encrypted File

This command decrypts the contents of contents.asc and displays them in the terminal.

# This example uses a key alias, but this can also be the ARN.
ENCRYPTED_FILE=contents.asc

aws kms decrypt \
  --ciphertext-blob fileb://<(cat ${ENCRYPTED_FILE} | base64 --decode) \
  --output text \
  --query Plaintext | base64 --decode

Re-Wrap Encrypted File with New Key

This command is useful if you rotate a key, or want to migrate to a new key.

It submits the encrypted data to KMS where it is decrypted with the old key, and then encrypted again with the new key.

This is a useful function as the client never receives decrypted contents.

NEW_KMS_KEY=alias/my-new-kms-key
aws kms re-encrypt \
  --ciphertext-blob fileb://<(cat ${ENCRYPTED_FILE} | base64 --decode) \
  --destination-key-id ${NEW_KMS_KEY} \
  --output text \
  --query CiphertextBlob > ${ENCRYPTED_FILE}.tmp

mv ${ENCRYPTED_FILE}.tmp ${ENCRYPTED_FILE}