Skip to content

Instantly share code, notes, and snippets.

@rexso
Last active August 31, 2015 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rexso/3026d1723c5f71e73f20 to your computer and use it in GitHub Desktop.
Save rexso/3026d1723c5f71e73f20 to your computer and use it in GitHub Desktop.
JavaScript Base64 encoder/decoder
var base64 = {
table: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
decode: function(str, urlSafe, autoPad) {
if(!(str = ('' + str)).length) {
throw 'invalid string length in base64.decode';
}
var b10, i, arr = [], len = str.length, padding = 0, table = (urlSafe ? this.table.substr(0, 62) + '-_' : this.table);
function charByte(c) {
if((c = table.indexOf(c.charAt(0))) == -1) {
throw 'invalid characater detected in base64.decode';
}
return c;
}
if(len == 0 || (len % 4 && !autoPad)) {
throw 'invalid base64 string detected in base64.decode';
} else if(len % 4 && autoPad) {
padding = 4 - (len % 4);
len -= 4;
} else if(str.charAt(len - 1) == '=') {
padding = (str.charAt(len - 2) == '=' ? 2 : 1);
len -= 4;
}
for(i = 0; i < len; ) {
b10 = ((charByte(str[i++]) << 18) | (charByte(str[i++]) << 12) | (charByte(str[i++]) << 6) | charByte(str[i++]));
arr.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xFF, b10 & 0xFF));
}
switch(padding) {
case 1:
b10 = ((charByte(str[i++]) << 18) | (charByte(str[i++]) << 12) | (charByte(str[i++]) << 6));
arr.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xFF));
break;
case 2:
b10 = ((charByte(str[i++]) << 18) | (charByte(str[i++]) << 12));
arr.push(String.fromCharCode(b10 >> 16));
break;
}
return arr.join('');
},
encode: function(str, urlSafe, stripPad) {
if(!(str = ('' + str)).length) {
throw 'invalid string length in base64.encode';
}
var b10, i, arr = [], len = (str.length - str.length % 3), table = (urlSafe ? this.table.substr(0, 62) + '-_' : this.table);
function charCode(c) {
if((c = c.charCodeAt(0)) > 255) {
throw 'invalid character detected in base64.encode';
}
return c;
}
for(i = 0; i < len; ) {
b10 = ((charCode(str[i++]) << 16) | (charCode(str[i++]) << 8) | charCode(str[i++]));
arr.push(table.charAt(b10 >> 18));
arr.push(table.charAt((b10 >> 12) & 0x3F));
arr.push(table.charAt((b10 >> 6) & 0x3F));
arr.push(table.charAt(b10 & 0x3F));
}
switch(str.length - len) {
case 1:
b10 = charCode(str[i]) << 16;
arr.push(table.charAt(b10 >> 18) + table.charAt((b10 >> 12) & 0x3F) + (stripPad ? '' : '=='));
break;
case 2:
b10 = ((charCode(str[i]) << 16) | (charCode(str[++i]) << 8));
arr.push(table.charAt(b10 >> 18) + table.charAt((b10 >> 12) & 0x3F) + table.charAt((b10 >> 6) & 0x3F) + (stripPad ? '' : '='));
break;
}
return arr.join('');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment