Last active
April 2, 2021 07:32
-
-
Save hr3lxphr6j/f00934e796a3c57beb2145209eae5c5c to your computer and use it in GitHub Desktop.
A script that can help you encrypt strings in the shell.
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
#!/bin/bash | |
set -o errexit | |
set -o pipefail | |
set -o nounset | |
OPENSSL=${OPENSSL:-$(which openssl)} | |
help() { | |
printf "$0 -h\n\tShow help.\n" | |
printf "$0 -t\n\tDo not show how to decrypt.\n" | |
printf "$0 -i INPUT\n\tInput.\n" | |
printf "$0 -k KEY\n\tKey.\n" | |
printf "$0 -c CIPHER\n\tCipher. Default \"aes-256-cbc\". See \"openssl enc -list\".\n" | |
printf "$0 -d DIGEST\n\tDigest. Default \"sha256\". See \"openssl dgst -list\".\n" | |
} | |
check_openssl() { | |
if [[ $(${OPENSSL} version) != LibreSSL\ 2.* ]]; then | |
return | |
fi | |
echo "The \"$($OPENSSL version)\" no support, please update LibreSSL to 3.x or use OpenSSL." | |
echo "You can specify the OpenSSL bin path through the environment variable \"OPENSSL\", for example:" | |
printf "\n\tOPENSSL=/usr/local/opt/openssl@1.1/bin/openssl $0\n\n" | |
exit 1 | |
} | |
main() { | |
check_openssl | |
while getopts "hi:k:c:d:t" OPT; do | |
case ${OPT} in | |
h) help && exit 0 ;; | |
t) _ht=0 ;; | |
i) _input="${OPTARG}" ;; | |
k) _key="${OPTARG}" ;; | |
c) _cipher="${OPTARG}" ;; | |
d) _digest="${OPTARG}" ;; | |
?) help && exit 1 ;; | |
esac | |
done | |
_cipher=${_cipher:-"aes-256-cbc"} | |
_digest=${_digest:-"sha256"} | |
if [[ ${_input:-} == "" ]]; then | |
printf "input is empty\n\n" | |
help | |
exit 1 | |
fi | |
if [[ ${_key:-} == "" ]]; then | |
printf "key is empty\n\n" | |
help | |
exit 1 | |
fi | |
_enc=$(printf "%s" "${_input}" | $OPENSSL enc -${_cipher} -pbkdf2 -k ${_key} -a -A) | |
_checksum=$(printf "%s" "${_input}" | openssl dgst -${_digest} -hmac ${_key} | awk '{print $2}') | |
printf "%30s: ${_input}\n%30s: ${_key}\n%30s: ${_enc}\n%30s: ${_checksum}\n" "Input" "Key" "Ciphertext(${_cipher})" "HMAC(${_digest})" | |
if [[ ${_ht:-1} == 1 ]]; then | |
printf "How to decrypt:\n\techo -n \"${_enc}\" | openssl ${_cipher} -pbkdf2 -k \"${_key}\" -a -A -d\n" | |
printf "How to verify:\n\ttest \"${_checksum}\" = \$(echo -n \"${_enc}\" | openssl ${_cipher} -pbkdf2 -k \"${_key}\" -a -A -d | openssl ${_digest} -hmac \"${_key}\" | awk '{print \$2}')\n" | |
fi | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: