Skip to content

Instantly share code, notes, and snippets.

@jmehnle
Created December 5, 2018 15:05
Show Gist options
  • Save jmehnle/51747d692549b12b7cc245613dc750cf to your computer and use it in GitHub Desktop.
Save jmehnle/51747d692549b12b7cc245613dc750cf to your computer and use it in GitHub Desktop.
AWS KMS string encryption/decryption convenience wrapper
#!/bin/bash
self="${0##*/}"
guid_re='[0-9a-z]{8}-([0-9a-z]{4}-){3}[0-9a-z]{12}'
usage () {
echo "Usage:"
echo " ${self} [--profile AWS_PROFILE] encrypt [--encryption-context KEY=VALUE] KEY_ID PLAINTEXT"
echo " ${self} [--profile AWS_PROFILE] decrypt [--encryption-context KEY=VALUE] CIPHERTEXT_BASE64"
}
if [[ "${#*}" == 0 ]]; then
usage
exit 1
fi
case "${1}" in
-h | --help | help)
usage
exit 0 ;;
esac
if [[ "${1}" == --profile ]]; then
aws_profile_opt="${1} ${2}"
shift 2
else
aws_profile_opt=""
fi
action="${1}"
shift
if [[ "${1}" == --encryption-context ]]; then
encryption_context_opt="${1} ${2}"
shift 2
else
encryption_context_opt=""
fi
case "${action}" in
encrypt)
key_id="${1}"
if [[ ! "${key_id}" =~ ^${guid_re}$ ]]; then
key_id="alias/${key_id}"
fi
plaintext="${2}"
shift 2
aws \
${aws_profile_opt} \
kms encrypt \
--key-id "${key_id}" \
--plaintext "fileb://"<(echo -n "${plaintext}") \
${encryption_context_opt} \
--output text \
--query CiphertextBlob
;;
decrypt)
ciphertext_base64="${1}"
shift
aws \
${aws_profile_opt} \
kms decrypt \
--ciphertext-blob fileb://<(base64 -D <<<"${ciphertext_base64}") \
${encryption_context_opt} \
--output text \
--query Plaintext \
| base64 -D
echo
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment