Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:45
Show Gist options
  • Save rfprod/38fdaa4b626d467b087a656fc41c876c to your computer and use it in GitHub Desktop.
Save rfprod/38fdaa4b626d467b087a656fc41c876c to your computer and use it in GitHub Desktop.
Base64 Coder
const Base64 = {
keys: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
encode(string){
let output = '';
for (let i = 0, max = string.length; i < max; i++) {
const code1 = string.charCodeAt(i);
i++;
const code2 = string.charCodeAt(i);
i++;
const code3 = string.charCodeAt(i);
let base1 = code1 >> 2;
let base2 = ((code1 & 3) << 4) | (code2 >> 4);
let base3 = ((code2 & 15) << 2) | (code3 >> 6);
let base4 = code3 & 63;
if (isNaN(code2)) {
base3 = 64;
base4 = 64;
} else if (isNaN(code3)) { base4 = 64; }
output += this.keys[base1] + this.keys[base2] + this.keys[base3] + this.keys[base4];
}
return output;
},
decode(string) {
let output = '';
for (let i = 0, max = string.length; i < max; i++) {
const base1 = this.keys.indexOf(string[i]);
i++;
const base2 = this.keys.indexOf(string[i]);
i++;
const base3 = this.keys.indexOf(string[i]);
i++;
const base4 = this.keys.indexOf(string[i]);
const code1 = (base1 << 2) | (base2 >> 4);
const code2 = ((base2 & 15) << 4) | (base3 >> 2);
const code3 = ((base3 & 3) << 6) | base4;
output += String.fromCharCode(code1) + String.fromCharCode(code2) + String.fromCharCode(code3);
}
return output;
},
};
/*
* USAGE
* Base64.encode('string');
* Base64.decode('HN0cmluZyEh');
*/

Base64 Coder

Encodes/decodes strings to/from Base64.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment