Created
May 25, 2024 06:01
-
-
Save edr3x/61971a4bcee24e245c216afc73f71204 to your computer and use it in GitHub Desktop.
url friendly base64 encoder and decoder
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 | |
encode() { | |
local input="$1" | |
if [ -z "$input" ]; then | |
input=$(cat) | |
fi | |
echo -n "$input" | base64 -w0 | tr '+/' '-_' | tr -d '=' | |
} | |
decode() { | |
local input="$1" | |
if [ -z "$input" ]; then | |
input=$(cat) | |
fi | |
local len=$(( ${#input} % 4 )) | |
if [ $len -eq 2 ]; then input="${input}==" | |
elif [ $len -eq 3 ]; then input="${input}=" | |
fi | |
echo -n "$input" | tr '_-' '/+' | base64 -d | |
} | |
if [ "$1" == "-d" ]; then | |
if [ -n "$2" ]; then | |
decode "$2" | |
else | |
decode | |
fi | |
else | |
if [ -n "$1" ]; then | |
encode "$1" | |
else | |
encode | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment