Base64 URL Safe Encoding / Decoding (RFC-7515)

A few days back I was required to encode some string in base 64 URL safe. After some research I found that there are several variants of base 64. The one implemented in the code below corresponds to RFC-7515. Here is the code:

function encodeBase64Url(str) {
    let s = new Buffer(str).toString('base64'); // Regular base64 encoder
    s = s.replace('=', ''); // Remove any trailing '='s
    s = s.replace('+', '-'); // 62nd char of encoding
    s = s.replace('/', '_'); // 63rd char of encoding
    return s;
}

function decodeBase64Url(str) {
    let s = str;
    s = s.replace('-', '+'); // 62nd char of encoding
    s = s.replace('_', '/'); // 63rd char of encoding
    switch (s.length % 4) // Pad with trailing '='s
    {
        case0: break; // No pad chars in this case
        case2: s += "=="; break; // Two pad chars
        case3: s += "="; break; // One pad char
        default: throw new System.Exception("Illegal base64url string!");
    }
    return new Buffer(s, 'base64').toString('ascii'); // Standard base64 decoder
}

let plainText = "Forge de Laguiole AIRBUS A350 is a 189 EUR knife";

console.log("Plaint text = " + plainText);

// Encoding to base64Url
let base64Url = encodeBase64Url(plainText);
console.log("Encoded to base64 = " + base64Url);

// Decoding from base64Url
let ascii = decodeBase64Url(base64Url);
console.log("Decoded from base64 = " + ascii);

if (plainText === ascii) {
    console.log("Everything went well!");
} else {
    console.log("Something went wrong!");
}

I hope is useful.

Sources::