Created
June 10, 2018 19:34
-
-
Save mrpapercut/ebc1fc5e61f4ca96fe441bfd1062f159 to your computer and use it in GitHub Desktop.
base64_encoder.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + | |
'abcdefghijklmnopqrstuvwxyz' + | |
'0123456789+/'; | |
const base64_encode = (input) => { | |
let length = input.length; | |
let [i, j, k, s] = [0, 0, 0, 0]; | |
let char_array_3 = new Array(3); | |
let char_array_4 = new Array(4); | |
const b64len = (length+2 - ((length+2) % 3)) * 4 / 3; | |
const b64str = new Array(b64len + 1); | |
while (length--) { | |
char_array_3[i++] = input[k++]; | |
if (i == 3) { | |
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; | |
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); | |
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); | |
char_array_4[3] = char_array_3[2] & 0x3f; | |
for (i = 0; i < 4; i++) | |
b64str[s++] = base64_chars[char_array_4[i]]; | |
i = 0; | |
} | |
} | |
if (i) { | |
for (j = i; j < 3; j++) | |
char_array_3[j] = '\0'; | |
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; | |
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); | |
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); | |
char_array_4[3] = char_array_3[2] & 0x3f; | |
for (j = 0; j < i + 1; j++) | |
b64str[s++] = base64_chars[char_array_4[j]]; | |
while (i++ < 3) | |
b64str[s++] = '='; | |
} | |
return b64str.join(''); | |
} | |
let _btoa = str => { | |
return base64_encode(str.split('').map(c => c.charCodeAt(0))); | |
} | |
console.log(_btoa(document.location.href)); | |
console.log(btoa(document.location.href)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment