Skip to main content

Base64 URL encode/decode functions in Bash.

#!/usr/bin/env bash

#
# base64url encode (https://gist.github.com/alvis/89007e96f7958f2686036d4276d28e47)
function base64url_encode {
  (if [ -z "$1" ]; then cat -; else echo -n "$1"; fi) \
    | openssl base64 -e -A \
    | sed s/\\+/-/g \
    | sed s/\\//_/g \
    | sed -E s/=+$//
}

#
# base64url decode (https://gist.github.com/alvis/89007e96f7958f2686036d4276d28e47)
function base64url_decode {
  INPUT=$(if [ -z "$1" ]; then echo -n "$(cat -)"; else echo -n "$1"; fi)
  MOD=$(($(echo -n "$INPUT" | wc -c) % 4))
  PADDING=$(if [ $MOD -eq 2 ]; then echo -n '=='; elif [ $MOD -eq 3 ]; then echo -n '='; fi)
  echo -n "$INPUT$PADDING" \
    | sed s/-/+/g \
    | sed s/_/\\//g \
    | openssl base64 -d -A
}

#
# Example
# $ base64url_encode "hello world"
# $ base64url_decode "aGVsbG8gd29ybGQ"