Skip to content

Instantly share code, notes, and snippets.

@catwell
Last active September 5, 2024 16:42
Show Gist options
  • Save catwell/3046205 to your computer and use it in GitHub Desktop.
Save catwell/3046205 to your computer and use it in GitHub Desktop.
Decoding Base64-URL without padding

Decoding Base64-URL without padding

1) Add padding

Divide the length of the input string by 4, take the remainder. If it is 2, add two = characters at the end. If it is 3, add one = character at the end.

You now have Base64-URL with padding.

2) Translate to Base64

Replace all - characters by + and all _ characters by /.

You now have Base64 with padding.

3) Decode Base64

Base64 decoding should be available as a library for your favorite language...

Examples

@catwell
Copy link
Author

catwell commented Sep 14, 2019

Thanks, it looks like the repository was renamed. I copy the script here in case the repo disappears (could happen since Moodstocks has belonged to Google for years now...)

#!/usr/bin/env bash
# Encode to / decode from Base64-URL without padding.

# USAGE:
# bash base64url.sh encode 'Hello!'
# bash base64url.sh decode SGVsbG8h

function encode {
  echo -n "$1" | openssl enc -a -A | tr -d '=' | tr '/+' '_-'
}

function decode {
  _l=$((${#1} % 4))
  if [ $_l -eq 2 ]; then _s="$1"'=='
  elif [ $_l -eq 3 ]; then _s="$1"'='
  else _s="$1" ; fi
  echo "$_s" | tr '_-' '/+' | openssl enc -d -a -A
}

case $1 in
  encode) encode "$2" ;;
  decode) decode $2 ;;
  e) encode "$2" ;;
  d) decode $2 ;;
esac

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment