Last active
December 29, 2023 04:11
-
-
Save hassy/96256cfde707fed40714c02b64f8049e to your computer and use it in GitHub Desktop.
Encrypt/decrypt files using AWS KMS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# License: MIT - https://opensource.org/licenses/MIT | |
# | |
# Usage: | |
# | |
# Encrypt a file: | |
# kms-vault encrypt My-Key-Alias some-file-i-want-encrypted.txt > topsecret.asc | |
# | |
# Decrypt a file: | |
# kms-vault decrypt topsecret.asc | |
# | |
# | |
# Requirements: AWS CLI, jq | |
# | |
# Your AWS profile / default profile needs to have access to the KMS key you want to use | |
# and the kms:ListAliases permission. | |
# | |
set -eu -o pipefail | |
command=$1 | |
if [[ $command = "encrypt" ]]; then | |
key_alias="$2" | |
key_info=$(aws kms list-aliases | jq -r ".Aliases[] | select(.AliasName | contains (\"$key_alias\"))") | |
echo "Using key:" 1>&2 | |
echo "$key_info" | jq 1>&2 | |
key_id=$(echo "$key_info" | jq -r .TargetKeyId) | |
plaintext_path="$3" | |
aws kms encrypt --key-id "$key_id" --plaintext "fileb://$plaintext_path" --query CiphertextBlob --output text | |
exit 0 | |
elif [[ $command = "decrypt" ]]; then | |
ciphertext_path="$2" | |
aws kms decrypt --ciphertext-blob fileb://<(cat $ciphertext_path | base64 --decode) --output text --query Plaintext | base64 --decode | |
exit 0 | |
else | |
echo "Unknown command: $command" | |
exit 1 | |
fi |
Thanks @jlis & glad you found it useful! I hope Github implement notifications on Gists some time soon, I only just saw your comment.
Bear in mind that KMS Encrypt is not particularly suitable for large files, as it sends the entire contents of the file to KMS to encrypt and then sends the base64-encoded encrypted file back, and there are size limits on the plaintext that KMS will encrypt.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for that nice snippet, saved me a ton of work.
One addition tho, since
base64 --decode
is not working on all distributions, I'd suggest switching topython -m base64 -d
(we can expect Python to be installed because of the AWS CLI).More information: tweag/aws-secrets#14