Skip to content

Instantly share code, notes, and snippets.

@Yaffle
Last active April 2, 2018 08:03
Show Gist options
  • Save Yaffle/1284012 to your computer and use it in GitHub Desktop.
Save Yaffle/1284012 to your computer and use it in GitHub Desktop.
javascript base64 encode/decode
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type="text/javascript">
var nativeAtob = window.atob;
var nativeBtoa = window.btoa;
// http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#atob
(function (global) {
"use strict";
var a64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var a256 = "";
var r64 = [];
var i = -1;
while (++i < 256) {
a256 += String.fromCharCode(i);
}
var counter = 63;
i = -1;
while (counter >= 0) {
var c = String.fromCharCode(++i);
r64[i] = a64.indexOf(c);
if (r64[i] !== -1) {
--counter;
}
}
function code(s, discard, alpha, beta, w1, w2) {
var buffer = 0;
var i = -1;
var length = s.length;
var result = '';
var bitsInBuffer = 0;
while (++i < length) {
var c = s.charCodeAt(i);
c = (alpha === null ? (c < 256 ? c : -1) : (c < alpha.length ? alpha[c] : -1));
if (c === -1) {
throw new RangeError();
}
buffer = (buffer << w1) + c;
bitsInBuffer += w1;
while (bitsInBuffer >= w2) {
bitsInBuffer -= w2;
var tmp = buffer >> bitsInBuffer;
result += beta.charAt(tmp);
buffer ^= tmp << bitsInBuffer;
}
}
if (!discard && bitsInBuffer > 0) {
result += beta.charAt(buffer << (w2 - bitsInBuffer));
}
return result;
}
global.btoa = function (s) {
s = String(s);
s = code(s, false, null, a64, 8, 6);
return s + "====".slice((s.length % 4) || 4);
};
global.atob = function (s) {
s = String(s);
var length = s.length;
var k = -1;
var result = "";
var i = 0;
while (++k < length + 1) {
if (k === length || s.charAt(k) === "=") {
var p = s.slice(i, k);
i = k + 1;
if (p.length % 4 === 1) {
throw new RangeError();
}
result += code(p, true, r64, a256, 6, 8);
}
}
return result;
};
}(this));
var decodeTests = [
['YW55IGNhcm5hbCBwbGVhc3VyZS4=', 'any carnal pleasure.'],
['YW55IGNhcm5hbCBwbGVhc3VyZQ==', 'any carnal pleasure'],
['YW55IGNhcm5hbCBwbGVhc3Vy', 'any carnal pleasur'],
[Array(1e4).join('YW55IGNhcm5hbCBwbGVhc3Vy'), Array(1e4).join('any carnal pleasur')], // ~24 kb input
['YW55IGNhcm5hbCBwbGVhc3U=', 'any carnal pleasu'],
['YW55IGNhcm5hbCBwbGVhcw==', 'any carnal pleas'],
['YW55IGNhcm5hbCBwbGVhcw', 'any carnal pleas'],
['\uaaaa', null],
['YQ', 'a'],
['YR', 'a'],
['', ''],
['YQA=', 'a\u0000'],
['YW55IGNhcm5hbCBwbGVhcw==YW55IGNhcm5hbCBwbGVhc3VyZS4=', 'any carnal pleasany carnal pleasure.'],
['YW55IGNhcm5hbCBwbGVhcw==YW55IGNhcm5hbCBwbGVhc3VyZS4', 'any carnal pleasany carnal pleasure.']
];
var encodeTests = [
['', ''],
['\x00', 'AA=='],
['\xff\xff', '//8='],
['any carnal pleasure.', 'YW55IGNhcm5hbCBwbGVhc3VyZS4='],
['any carnal pleasure', 'YW55IGNhcm5hbCBwbGVhc3VyZQ=='],
['any carnal pleasur', 'YW55IGNhcm5hbCBwbGVhc3Vy'],
[Array(1e4).join('any carnal pleasur'), Array(1e4).join('YW55IGNhcm5hbCBwbGVhc3Vy')], // ~24 kb output
['any carnal pleasu', 'YW55IGNhcm5hbCBwbGVhc3U='],
['any carnal pleas', 'YW55IGNhcm5hbCBwbGVhcw=='],
['a', 'YQ=='],
['', ''],
['\uaaaa', null],
['a\u0000', 'YQA=']
];
if (!window.console) {
window.console = {
log: function (x) {
document.body.appendChild(document.createTextNode(x));
document.body.appendChild(document.createElement('br'));
}
};
}
function runTests(tests, func, name) {
var i, r, t = +new Date();
for (i = 0; i < tests.length; i++) {
try {
r = func(tests[i][0]);
} catch (e) {
r = null;
}
if (r !== tests[i][1]) {
console.log(i + ': ' + name + '(' + tests[i][0] + ') === ' + r + '(expected: ' + tests[i][1] + ')');
}
}
t = +new Date() - t;
console.log(name + ' - ' + t + 'ms');
}
setTimeout(function () {
if (window.atob) {
runTests(decodeTests, nativeAtob, 'window.atob - native');
}
runTests(decodeTests, window.atob, 'window.atob');
if (window.btoa) {
runTests(encodeTests, nativeBtoa, 'window.btoa - native');
}
runTests(encodeTests, window.btoa, 'window.btoa');
console.log('finished');
}, 1);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment