Base64 Url Tokens in Javascript

encodeUrlToken: function (input) {
    var ret = Base64.encode(input).replace(/\+/g, "-").replace(/\//g, "_");
    if (ret.length == 0)
        return "";
    var noPadding = ret.replace(/=+$/, ""); 
    return noPadding + (ret.length - noPadding.length).toString();
}

This is great if you want to encode some unicode to Base64 in javascript:

http://www.webtoolkit.info/javascript-base64.html

But you cannot use the result reliably as part of a url, should you wish to do so.
In .net you have

HttpServerUtility.UrlTokenEncode

which just does a base64 and then swaps out certain characters so you can.
Here are two small mods to the above javascript to do the same:

encodeUrlToken: function (input) {
    var ret = Base64.encode(input).replace(/\+/g, "-").replace(/\//g, "_");
    if (ret.length == 0)
        return "";
    var noPadding = ret.replace(/=+$/, ""); 
    return noPadding + (ret.length - noPadding.length).toString();
},

decodeUrlToken: function (input) {
    var ec = parseInt(input.substring(input.length - 1));
    var temp = input.replace(/\-/g, "+").replace(/\_/g, "/");
    temp = temp.substring(0, temp.length - 1); 
    return Base64.decode(temp + "===".substring(0, ec));
},

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>