1// Base64 JavaScript decoder
2// Copyright (c) 2008-2018 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(function (undefined) {
17"use strict";
18
19var Base64 = {},
20 decoder;
21
22Base64.decode = function (a) {
23 var i;
24 if (decoder === undefined) {
25 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
26 ignore = "= \f\n\r\t\u00A0\u2028\u2029";
27 decoder = [];
28 for (i = 0; i < 64; ++i)
29 decoder[b64.charAt(i)] = i;
30 for (i = 0; i < ignore.length; ++i)
31 decoder[ignore.charAt(i)] = -1;
32 // RFC 3548 URL & file safe encoding
33 decoder['-'] = decoder['+'];
34 decoder['_'] = decoder['/'];
35 }
36 var out = [];
37 var bits = 0, char_count = 0;
38 for (i = 0; i < a.length; ++i) {
39 var c = a.charAt(i);
40 if (c == '=')
41 break;
42 c = decoder[c];
43 if (c == -1)
44 continue;
45 if (c === undefined)
46 throw 'Illegal character at offset ' + i;
47 bits |= c;
48 if (++char_count >= 4) {
49 out[out.length] = (bits >> 16);
50 out[out.length] = (bits >> 8) & 0xFF;
51 out[out.length] = bits & 0xFF;
52 bits = 0;
53 char_count = 0;
54 } else {
55 bits <<= 6;
56 }
57 }
58 switch (char_count) {
59 case 1:
60 throw "Base64 encoding incomplete: at least 2 bits missing";
61 case 2:
62 out[out.length] = (bits >> 10);
63 break;
64 case 3:
65 out[out.length] = (bits >> 16);
66 out[out.length] = (bits >> 8) & 0xFF;
67 break;
68 }
69 return out;
70};
71
72Base64.re = /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;
73Base64.unarmor = function (a) {
74 var m = Base64.re.exec(a);
75 if (m) {
76 if (m[1])
77 a = m[1];
78 else if (m[2])
79 a = m[2];
80 else
81 throw "RegExp out of sync";
82 }
83 return Base64.decode(a);
84};
85
86// export globals
87if (typeof module !== 'undefined') { module.exports = Base64; } else { window.Base64 = Base64; }
88})();