Saturday, December 29, 2007

JavaScript: Decode from Base64

Once again, I will not take credit of this one too...

// ***
// Decode from Base64
// Warning: Do not use for larger content as the loop might take a while
// ***
function base64Decode(data)
{
data = data.replace(/[^a-z0-9\+\/=]/ig, '');
if (typeof(atob) == 'function') return atob(data);
var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var byte1, byte2, byte3;
var ch1, ch2, ch3, ch4;
var result = new Array();
var j=0;
while ((data.length%4) != 0) {
data += '=';
}

for (var i=0; i <data.length; i+=4) {
ch1 = b64_map.indexOf(data.charAt(i));
ch2 = b64_map.indexOf(data.charAt(i+1));
ch3 = b64_map.indexOf(data.charAt(i+2));
ch4 = b64_map.indexOf(data.charAt(i+3));

byte1 = (ch1 <<>> 4);
byte2 = ((ch2 & 15) <<>> 2);
byte3 = ((ch3 & 3) << 6) | ch4;

result[j++] = String.fromCharCode(byte1);
if (ch3 != 64) result[j++] = String.fromCharCode(byte2);
if (ch4 != 64) result[j++] = String.fromCharCode(byte3);
}

return result.join('');
}

4 comments:

  1. Why the check for an "atob" function?

    We're seeing exactly this function (save it being randomly renamed server-side on serving) being used on malicious web pages and it seems the bad guys have copied it from your site, or from the place you got the original. According to Google, the test for the "atob" function is quite unique to your/the original code -- the few other hits on that code snippet are pages posted later than this page of yours so I'm intrigued as to where you originally found this.

    ReplyDelete
  2. As I mentioned Nick, I do not take credit for this code. So I am not sure where the 'atob' function originated from. Sorry if that did not help.

    ReplyDelete
  3. function decode_base64(s) {
    var e={},i,k,v=[],r='',w=String.fromCharCode,n=[[65,91],[97,123],[48,58],[47,48],[43,44]];

    for(z in n){for(i=n[z][0];i=8){r+=w((b>>>(l-=8))%256);}
    }
    }

    return r;
    }

    .. Sniper

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.