Skip to content

Instantly share code, notes, and snippets.

@stokito
Last active February 12, 2022 09:46
Show Gist options
  • Save stokito/18ce554bd53bdb6355670066d5ae9943 to your computer and use it in GitHub Desktop.
Save stokito/18ce554bd53bdb6355670066d5ae9943 to your computer and use it in GitHub Desktop.
Base64 in shell scripts (ash,bash)

Base64 URL safe in shell scripts

The Base64 url safe already supported by basenc command. But it may be not pre-installed on many platfroms.

You can call base64 command but there is a pitfalls:

  • On most Linux distros the base64 command comes from coreutils package. And it already have a basenc command

  • On OpenWrt the base64 is not installed by default and comes from coreutils-base64 package and the baseenc command from coreutils-baseenc

  • You can enable the base64 in BusyBox i.e. if you building the OpenWrt image yourself.

  • You may use openssl base64 or openssl enc -base64 see docs but it will read by lines so you must also specify -A param.

  • On MacOS the -d decode flag must be in upper case base64 -D so most users use --decode flag. Previously MacOS used the -d for debug but it's not clear who ever used it. Then Applce just removed the -d param but again it's not clear why they don't changed it to be compatible with coreutils. Don't use any MacOS products. Just don't.

  • Python also can be usedpython3 -m base64 -d

  • https://www.yuryoparin.com/2014/05/base64url-in-bash.html pure bash scripts: no any requiteremnts. But works too slowly.

  • https://gist.github.com/woniuzfb/717dc5dd19374bf9b6cd38078753a9ac wrapper uppon base64 to decode base64 url safe

Shell functions to convert base64 url safe to regular base64:

base64_padding()
{
  local len=$(( ${#1} % 4 ))
  local padded_b64=''
  if [ ${len} = 2 ]; then
    padded_b64="${1}=="
  elif [ ${len} = 3 ]; then
    padded_b64="${1}="
  else
    padded_b64="${1}"
  fi
  echo -n "$padded_b64"
}

base64url_to_b64()
{
  base64_padding "${1}" | tr -- '-_' '+/'
}

I created tickets to fix the discrapanceies:

See also

https://github.com/acmesh-official/acme.sh/blob/master/acme.sh#L1582

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