I think the most efficient way of doing Base64/Base64URL decoding is to decode directly in a function instead of changing Base64URL into Base64 and then decoding it. I wrote a function that can decode both Base64 and Base64URL directly without any other dependency.
const PADCHAR = '=';
const B64index = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,62,63,62,62,63,52,53,54,55,56,57,58,59,60,61, 0, 0,
0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
15,16,17,18,19,20,21,22,23,24,25, 0, 0, 0, 0,63, 0,26,27,28,
29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,
49,50,51];
function b64decode(s) {
const len = s.length;
if (len === 0) return s;
const padding = (s.charAt(len-1) === PADCHAR);
const pad = padding || ((len % 4) > 0);
const L = (Math.floor((len+3)/4)-pad)*4;
var x = [];
for (i = 0; i < L; i += 4)
{
var n = B64index[s.charCodeAt(i)] << 18 |
B64index[s.charCodeAt(i+1)] << 12 |
B64index[s.charCodeAt(i+2)] << 6 |
B64index[s.charCodeAt(i+3)];
x.push(String.fromCharCode(n >> 16, (n >> 8) & 0xff, n & 0xff));
}
if (pad)
{
var n = B64index[s.charCodeAt(L)] << 18 |
B64index[s.charCodeAt(L+1)] << 12;
x.push(String.fromCharCode(n >> 16));
if (len > L + 2 && ((s.charAt(L+2) != PADCHAR) || !padding))
{
n |= B64index[s.charCodeAt(L+2)] << 6;
x.push(String.fromCharCode((n >> 8) & 0xff));
}
}
return x.join('');
}
To use this function to decode the Base64URL string, I use JWT token as an example. First, I split the token. Then, I decode the JWT payload and then parse it into JSON object.
const elements = token.split('.');
const payload = JSON.parse(b64decode(elements[1]));
Base64Url
encoding is specified in RFC 4648, The Base16, Base32, and Base64 Data Encodings. The only difference betweenBase64
andBase64Url
is two values (62 and 63). Just replace"+"
with"-"
and"/"
with"_"
. – Ankylosaurvar base64url = function(aStr) { return btoa(aStr.replace(/\+/g,'-').replace(/\//g,'_')).replace(/\=+$/m,'') }
with the trialing=
's stripped? – Asclepiadean