1// Base64 JavaScript decoder
2// Copyright (c) 2008-2014 Lapo Luchini <lapo@lapo.it>
3
4// Permission to use, copy, modify, and/or distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
17(function (undefined) {
18"use strict";
19
20var Base64 = {},
21 decoder;
22
23Base64.decode = function (a) {
24 var i;
25 if (decoder === undefined) {
26 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
27 ignore = "= \f\n\r\t\u00A0\u2028\u2029";
28 decoder = [];
29 for (i = 0; i < 64; ++i)
30 decoder[b64.charAt(i)] = i;
31 for (i = 0; i < ignore.length; ++i)
32 decoder[ignore.charAt(i)] = -1;
33 }
34 var out = [];
35 var bits = 0, char_count = 0;
36 for (i = 0; i < a.length; ++i) {
37 var c = a.charAt(i);
38 if (c == '=')
39 break;
40 c = decoder[c];
41 if (c == -1)
42 continue;
43 if (c === undefined)
44 throw 'Illegal character at offset ' + i;
45 bits |= c;
46 if (++char_count >= 4) {
47 out[out.length] = (bits >> 16);
48 out[out.length] = (bits >> 8) & 0xFF;
49 out[out.length] = bits & 0xFF;
50 bits = 0;
51 char_count = 0;
52 } else {
53 bits <<= 6;
54 }
55 }
56 switch (char_count) {
57 case 1:
58 throw "Base64 encoding incomplete: at least 2 bits missing";
59 case 2:
60 out[out.length] = (bits >> 10);
61 break;
62 case 3:
63 out[out.length] = (bits >> 16);
64 out[out.length] = (bits >> 8) & 0xFF;
65 break;
66 }
67 return out;
68};
69
70Base64.re = /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;
71Base64.unarmor = function (a) {
72 var m = Base64.re.exec(a);
73 if (m) {
74 if (m[1])
75 a = m[1];
76 else if (m[2])
77 a = m[2];
78 else
79 throw "RegExp out of sync";
80 }
81 return Base64.decode(a);
82};
83
84// export globals
85if (typeof module !== 'undefined') { module.exports = Base64; } else { window.Base64 = Base64; }
86})();