Skip to content

Instantly share code, notes, and snippets.

@rubenhortas
Last active March 19, 2024 20:56
Show Gist options
  • Save rubenhortas/be093c721411aaafba95df7e4bcecf09 to your computer and use it in GitHub Desktop.
Save rubenhortas/be093c721411aaafba95df7e4bcecf09 to your computer and use it in GitHub Desktop.
Bash script to encode and decode to base64url
#!/usr/bin/env bash
# Encodes/decodes a string to/from base64url.
print_help() {
echo "Usage: $(basename "$0") [-d] STRING"
echo
echo "Without -d encodes the string to base64url."
echo
echo " -d decodes the string from base64url (or base64)"
echo " -h shows this help"
exit 0
}
if [ "$#" -gt 0 ] && [ "$#" -le 2 ]
then
decode=false
while getopts "dh:" flag
do
case "${flag}" in
d) decode=true;;
h) print_help;;
*) print_help;;
esac
done
if [ "$decode" = false ]
then
if [ "$#" -eq 1 ]
then
echo "$1" | base64 | tr '/+' '_+' && exit 0
fi
else
if [ "$#" -eq 2 ]
then
# Avoid base64 "invalid input": https://unix.stackexchange.com/questions/631501/base64-d-decodes-but-says-invalid-input
# "fold -w 4" split every 4 characters into separate lines
# "sed '$ d'" deletes the last line (the extraneous padding)
# "tr -d '\n'" joins all lines
# " sed '$a\'" adds a new line, only, if doesn't exists
echo "$2"==== | fold -w 4 | sed '$ d' | tr -d '\n' | tr '_-' '/+' | base64 -d | sed '$a\' && exit 0
fi
fi
fi
print_help
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment