Skip to content

Instantly share code, notes, and snippets.

@woniuzfb
Forked from toonetown/base64
Last active March 19, 2019 17:33
Show Gist options
  • Save woniuzfb/717dc5dd19374bf9b6cd38078753a9ac to your computer and use it in GitHub Desktop.
Save woniuzfb/717dc5dd19374bf9b6cd38078753a9ac to your computer and use it in GitHub Desktop.
Adds an option to encode/decode url-safe base64
###
# Shell script which adds the ability to encode/decode web-safe URLs in base64. Do this by specifying
#
#!/bin/bash
ARGS=()
BAD_CHARS="+/="
SAFE_CHARS="-_ "
URL="n"; CONVERT="n"; DECODE="n"; IN="-"; OUT="-"; HELP="n"
while (($#)); do
case "${1}" in
-h | --help)
HELP="y"
ARGS+=("--help")
;;
-D | --decode)
DECODE="y"
ARGS+=("${1}") # macos -D, linux -d, base64 version?? better use --decode
;;
-i | --input=*)
if [ "${1}" == "-i" ]; then shift; fi
IN="${1#--input=}"
;;
-o | --output=*)
if [ "${1}" == "-o" ]; then shift; fi
OUT="${1#--output=}"
;;
-u | --url)
URL="y"
;;
-c | --convert)
CONVERT="y"
;;
*)
ARGS+=("${1}")
;;
esac
shift
done
# Converts the stream (of unsafe characters) to safe characters
function to_safe {
tr -- "${BAD_CHARS}" "${SAFE_CHARS}" | sed -e 's/ *$//g'
}
# Converts the stream (of safe characters) to unsafe characters
function from_safe {
awk '{ L=length($1)/4; L=int((L==int(L))?L:int(L)+1)*4; printf "%-*s\n", L, $1; }' \
| tr -- "${SAFE_CHARS}" "${BAD_CHARS}"
}
# Handle convert-only
if [ "${CONVERT}" == "y" ]; then
if [ "${OUT}" == "-" ]; then OUT="/dev/stdout"; fi
if [ "${DECODE}" == "y" ]; then
cat "${IN}" | from_safe > "${OUT}"
else
cat "${IN}" | to_safe > "${OUT}"
fi
exit $?
fi
# Handle if we specified url-safe
if [ "${URL}" == "y" ]; then
if [ "${DECODE}" == "y" ]; then
cat "${IN}" | from_safe | /usr/bin/base64 "${ARGS[@]}" -o "${OUT}"
else
if [ "${OUT}" == "-" ]; then OUT="/dev/stdout"; fi
/usr/bin/base64 "${ARGS[@]}" -i "${IN}" | to_safe > "${OUT}"
fi
exit $?
fi
# Just pass it through - but add our help
/usr/bin/base64 "${ARGS[@]}" -i "${IN}" -o "${OUT}"
RET=$?
if [ "${HELP}" == "y" ]; then
echo " -u, --url encode/decode url-safe strings" >&2
echo " -c, --convert without -D, converts to url-safe strings" >&2
echo " with -D, converts from url-safe strings" >&2
fi
exit ${RET}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment