tl;dr
Use basenc(1)
from coreutils
:
$ printf "xs?>>>" | basenc --base64
eHM/Pj4+
$ printf "xs?>>>" | basenc --base64url
eHM_Pj4-
As with base64(1)
, add the -d
switch to decode.
A bit of explanation
Recent versions of coreutils
include basenc(1)
which supports several different encodings. From its help screen:
--base64 same as 'base64' program (RFC4648 section 4)
--base64url file- and url-safe base64 (RFC4648 section 5)
--base32 same as 'base32' program (RFC4648 section 6)
--base32hex extended hex alphabet base32 (RFC4648 section 7)
--base16 hex encoding (RFC4648 section 8)
--base2msbf bit string with most significant bit (msb) first
--base2lsbf bit string with least significant bit (lsb) first
--z85 ascii85-like encoding (ZeroMQ spec:32/Z85);
when encoding, input length must be a multiple of 4;
when decoding, input length must be a multiple of 5
Here is a string that illustrates the difference:
s="xs?>>>"
As binary:
$ printf "%s" "$s" | xxd -b -c1 | cut -d' ' -f2 | nl
1 01111000
2 01110011
3 00111111
4 00111110
5 00111110
6 00111110
And as 6 bit blocks (as base64 reads the data):
$ printf "%s" "$s" | xxd -b -c1 | cut -d' ' -f2 | tr -d '\n' | fold -w6 | nl
1 011110
2 000111
3 001100
4 111111
5 001111
6 100011
7 111000
8 111110
Note that block 4 and block 8 map to /
and +
respectively (Base64 table on Wikipedia):
basenc
is not available anymore atlease as of ubuntu20.04
– Mickeymicki