Mercurial > eldonilo > lightstring
comparison base64.js @ 0:96898e3812a5
initial push
author | Sonny Piers <sonny.piers@gmail.com> |
---|---|
date | Sun, 18 Dec 2011 19:03:28 +0100 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:96898e3812a5 |
---|---|
1 // This code was written by Tyler Akins and has been placed in the | |
2 // public domain. It would be nice if you left this header intact. | |
3 // Base64 code from Tyler Akins -- http://rumkin.com | |
4 | |
5 var Base64 = (function () { | |
6 var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; | |
7 | |
8 var obj = { | |
9 /** | |
10 * Encodes a string in base64 | |
11 * @param {String} input The string to encode in base64. | |
12 */ | |
13 encode: function (input) { | |
14 var output = ""; | |
15 var chr1, chr2, chr3; | |
16 var enc1, enc2, enc3, enc4; | |
17 var i = 0; | |
18 | |
19 do { | |
20 chr1 = input.charCodeAt(i++); | |
21 chr2 = input.charCodeAt(i++); | |
22 chr3 = input.charCodeAt(i++); | |
23 | |
24 enc1 = chr1 >> 2; | |
25 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); | |
26 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); | |
27 enc4 = chr3 & 63; | |
28 | |
29 if (isNaN(chr2)) { | |
30 enc3 = enc4 = 64; | |
31 } else if (isNaN(chr3)) { | |
32 enc4 = 64; | |
33 } | |
34 | |
35 output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + | |
36 keyStr.charAt(enc3) + keyStr.charAt(enc4); | |
37 } while (i < input.length); | |
38 | |
39 return output; | |
40 }, | |
41 | |
42 /** | |
43 * Decodes a base64 string. | |
44 * @param {String} input The string to decode. | |
45 */ | |
46 decode: function (input) { | |
47 var output = ""; | |
48 var chr1, chr2, chr3; | |
49 var enc1, enc2, enc3, enc4; | |
50 var i = 0; | |
51 | |
52 // remove all characters that are not A-Z, a-z, 0-9, +, /, or = | |
53 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); | |
54 | |
55 do { | |
56 enc1 = keyStr.indexOf(input.charAt(i++)); | |
57 enc2 = keyStr.indexOf(input.charAt(i++)); | |
58 enc3 = keyStr.indexOf(input.charAt(i++)); | |
59 enc4 = keyStr.indexOf(input.charAt(i++)); | |
60 | |
61 chr1 = (enc1 << 2) | (enc2 >> 4); | |
62 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); | |
63 chr3 = ((enc3 & 3) << 6) | enc4; | |
64 | |
65 output = output + String.fromCharCode(chr1); | |
66 | |
67 if (enc3 != 64) { | |
68 output = output + String.fromCharCode(chr2); | |
69 } | |
70 if (enc4 != 64) { | |
71 output = output + String.fromCharCode(chr3); | |
72 } | |
73 } while (i < input.length); | |
74 | |
75 return output; | |
76 } | |
77 }; | |
78 | |
79 return obj; | |
80 })(); |