Last active
April 14, 2020 20:35
-
-
Save xandout/e7ad96c4ae23d4b9fc78b0e371904f30 to your computer and use it in GitHub Desktop.
Encrypt and decrypt strings in bash
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
# https://superuser.com/a/1508949/266021 | |
# Accept STDIN as $1 | |
# Add the content of this to your RC or source the file | |
VAULT_PASS=${VAULT_PASS:-password} | |
denc() { | |
if [[ $# -eq 0 ]] #in case of standard input | |
then | |
input=$(</dev/stdin) | |
else | |
input=$(echo "${@}") | |
fi | |
stripped_pre="${input/\#vault\:/}" | |
stripped="${stripped_pre/\:vault\#/}" | |
echo "$stripped" | base64 -d | gpg --yes --batch --passphrase=${VAULT_PASS} -q - | base64 -d | |
} | |
enc() { | |
if [[ $# -eq 0 ]] #in case of standard input | |
then | |
input=$(base64 </dev/stdin | tr -d '\n') | |
else | |
input=$(echo "${@}" | base64 | tr -d '\n' ) | |
fi | |
encrypted=$(echo "${input}" | gpg --yes --batch --passphrase=${VAULT_PASS} -c -q - | base64 | tr -d '\n') | |
wrapped="#vault:${encrypted}:vault#" | |
decrypted=$(denc "$wrapped") | |
if [[ "${input}" == "${decrypted}" || true ]]; then | |
echo "${wrapped}" | |
else | |
echo "Vault check failed, verify VAULT_PASS" | |
fi | |
} | |
enc dog | denc | |
echo dog | enc | denc | |
# EDITS: Now supports cating files with spaces. Still doesn't support binary files | |
# USAGE | |
# dev@home # echo dog | enc | denc | |
# dog | |
# enc "$(cat ~/.ssh/id_rsa)" | denc | |
# cat ~/.ssh/id_rsa | enc | denc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment