Wentao Shang | 882e34e | 2013-01-05 02:49:51 -0800 | [diff] [blame^] | 1 | // Base64 JavaScript decoder
|
| 2 | // Copyright (c) 2008 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 | Base64 = {};
|
| 17 |
|
| 18 | Base64.decode = function(a) {
|
| 19 | if (Base64.decoder == undefined) {
|
| 20 | var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
| 21 | var allow = "= \f\n\r\t\u00A0\u2028\u2029";
|
| 22 | var dec = [];
|
| 23 | for (var i = 0; i < 64; ++i)
|
| 24 | dec[b64.charAt(i)] = i;
|
| 25 | for (var i = 0; i < allow.length; ++i)
|
| 26 | dec[allow.charAt(i)] = -1;
|
| 27 | Base64.decoder = dec;
|
| 28 | }
|
| 29 | var out = [];
|
| 30 | var bits = 0, char_count = 0;
|
| 31 | for (var i = 0; i < a.length; ++i) {
|
| 32 | var c = a.charAt(i);
|
| 33 | if (c == '=')
|
| 34 | break;
|
| 35 | c = Base64.decoder[c];
|
| 36 | if (c == -1)
|
| 37 | continue;
|
| 38 | if (c == undefined)
|
| 39 | throw 'Illegal character at offset ' + i;
|
| 40 | bits |= c;
|
| 41 | if (++char_count >= 4) {
|
| 42 | out[out.length] = (bits >> 16);
|
| 43 | out[out.length] = (bits >> 8) & 0xFF;
|
| 44 | out[out.length] = bits & 0xFF;
|
| 45 | bits = 0;
|
| 46 | char_count = 0;
|
| 47 | } else {
|
| 48 | bits <<= 6;
|
| 49 | }
|
| 50 | }
|
| 51 | switch (char_count) {
|
| 52 | case 1:
|
| 53 | throw "Base64 encoding incomplete: at least 2 bits missing";
|
| 54 | break;
|
| 55 | case 2:
|
| 56 | out[out.length] = (bits >> 10);
|
| 57 | break;
|
| 58 | case 3:
|
| 59 | out[out.length] = (bits >> 16);
|
| 60 | out[out.length] = (bits >> 8) & 0xFF;
|
| 61 | break;
|
| 62 | }
|
| 63 | return out;
|
| 64 | }
|
| 65 |
|
| 66 | Base64.re = /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;
|
| 67 | Base64.unarmor = function(a) {
|
| 68 | var m = Base64.re.exec(a);
|
| 69 | if (m) {
|
| 70 | if (m[1])
|
| 71 | a = m[1];
|
| 72 | else if (m[2])
|
| 73 | a = m[2];
|
| 74 | else
|
| 75 | throw "RegExp out of sync";
|
| 76 | }
|
| 77 | return Base64.decode(a);
|
| 78 | }
|