OSDN Git Service

Change generation of files/paths in images dir to use FileManager
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / utilities / Base64.java
1 package cx.fbn.nevernote.utilities;\r
2 \r
3 \r
4 /**\r
5  * <p>Encodes and decodes to and from Base64 notation.</p>\r
6  * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>\r
7  * \r
8  * <p>Example:</p>\r
9  * \r
10  * <code>String encoded = Base64.encode( myByteArray );</code>\r
11  * <br />\r
12  * <code>byte[] myByteArray = Base64.decode( encoded );</code>\r
13  *\r
14  * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass \r
15  * several pieces of information to the encoder. In the "higher level" methods such as \r
16  * encodeBytes( bytes, options ) the options parameter can be used to indicate such \r
17  * things as first gzipping the bytes before encoding them, not inserting linefeeds,\r
18  * and encoding using the URL-safe and Ordered dialects.</p>\r
19  *\r
20  * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,\r
21  * Section 2.1, implementations should not add line feeds unless explicitly told\r
22  * to do so. I've got Base64 set to this behavior now, although earlier versions\r
23  * broke lines by default.</p>\r
24  *\r
25  * <p>The constants defined in Base64 can be OR-ed together to combine options, so you \r
26  * might make a call like this:</p>\r
27  *\r
28  * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>\r
29  * <p>to compress the data before encoding it and then making the output have newline characters.</p>\r
30  * <p>Also...</p>\r
31  * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>\r
32  *\r
33  *\r
34  *\r
35  * <p>\r
36  * Change Log:\r
37  * </p>\r
38  * <ul>\r
39  *  <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing\r
40  *   the Base64.OutputStream closed the Base64 encoding (by padding with equals\r
41  *   signs) too soon. Also added an option to suppress the automatic decoding\r
42  *   of gzipped streams. Also added experimental support for specifying a\r
43  *   class loader when using the\r
44  *   {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}\r
45  *   method.</li>\r
46  *  <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java\r
47  *   footprint with its CharEncoders and so forth. Fixed some javadocs that were\r
48  *   inconsistent. Removed imports and specified things like java.io.IOException\r
49  *   explicitly inline.</li>\r
50  *  <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the\r
51  *   final encoded data will be so that the code doesn't have to create two output\r
52  *   arrays: an oversized initial one and then a final, exact-sized one. Big win\r
53  *   when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not\r
54  *   using the gzip options which uses a different mechanism with streams and stuff).</li>\r
55  *  <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some\r
56  *   similar helper methods to be more efficient with memory by not returning a\r
57  *   String but just a byte array.</li>\r
58  *  <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments\r
59  *   and bug fixes queued up and finally executed. Thanks to everyone who sent\r
60  *   me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.\r
61  *   Much bad coding was cleaned up including throwing exceptions where necessary \r
62  *   instead of returning null values or something similar. Here are some changes\r
63  *   that may affect you:\r
64  *   <ul>\r
65  *    <li><em>Does not break lines, by default.</em> This is to keep in compliance with\r
66  *      <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>\r
67  *    <li><em>Throws exceptions instead of returning null values.</em> Because some operations\r
68  *      (especially those that may permit the GZIP option) use IO streams, there\r
69  *      is a possiblity of an java.io.IOException being thrown. After some discussion and\r
70  *      thought, I've changed the behavior of the methods to throw java.io.IOExceptions\r
71  *      rather than return null if ever there's an error. I think this is more\r
72  *      appropriate, though it will require some changes to your code. Sorry,\r
73  *      it should have been done this way to begin with.</li>\r
74  *    <li><em>Removed all references to System.out, System.err, and the like.</em>\r
75  *      Shame on me. All I can say is sorry they were ever there.</li>\r
76  *    <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed\r
77  *      such as when passed arrays are null or offsets are invalid.</li>\r
78  *    <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.\r
79  *      This was especially annoying before for people who were thorough in their\r
80  *      own projects and then had gobs of javadoc warnings on this file.</li>\r
81  *   </ul>\r
82  *  <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug\r
83  *   when using very small files (~< 40 bytes).</li>\r
84  *  <li>v2.2 - Added some helper methods for encoding/decoding directly from\r
85  *   one file to the next. Also added a main() method to support command line\r
86  *   encoding/decoding from one file to the next. Also added these Base64 dialects:\r
87  *   <ol>\r
88  *   <li>The default is RFC3548 format.</li>\r
89  *   <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates\r
90  *   URL and file name friendly format as described in Section 4 of RFC3548.\r
91  *   http://www.faqs.org/rfcs/rfc3548.html</li>\r
92  *   <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates\r
93  *   URL and file name friendly format that preserves lexical ordering as described\r
94  *   in http://www.faqs.org/qa/rfcc-1940.html</li>\r
95  *   </ol>\r
96  *   Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>\r
97  *   for contributing the new Base64 dialects.\r
98  *  </li>\r
99  * \r
100  *  <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added\r
101  *   some convenience methods for reading and writing to and from files.</li>\r
102  *  <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems\r
103  *   with other encodings (like EBCDIC).</li>\r
104  *  <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the\r
105  *   encoded data was a single byte.</li>\r
106  *  <li>v2.0 - I got rid of methods that used booleans to set options. \r
107  *   Now everything is more consolidated and cleaner. The code now detects\r
108  *   when data that's being decoded is gzip-compressed and will decompress it\r
109  *   automatically. Generally things are cleaner. You'll probably have to\r
110  *   change some method calls that you were making to support the new\r
111  *   options format (<tt>int</tt>s that you "OR" together).</li>\r
112  *  <li>v1.5.1 - Fixed bug when decompressing and decoding to a             \r
113  *   byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.      \r
114  *   Added the ability to "suspend" encoding in the Output Stream so        \r
115  *   you can turn on and off the encoding if you need to embed base64       \r
116  *   data in an otherwise "normal" stream (like an XML file).</li>  \r
117  *  <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.\r
118  *      This helps when using GZIP streams.\r
119  *      Added the ability to GZip-compress objects before encoding them.</li>\r
120  *  <li>v1.4 - Added helper methods to read/write files.</li>\r
121  *  <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>\r
122  *  <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream\r
123  *      where last buffer being read, if not completely full, was not returned.</li>\r
124  *  <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>\r
125  *  <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>\r
126  * </ul>\r
127  *\r
128  * <p>\r
129  * I am placing this code in the Public Domain. Do with it as you will.\r
130  * This software comes with no guarantees or warranties but with\r
131  * plenty of well-wishing instead!\r
132  * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>\r
133  * periodically to check for updates or to contribute improvements.\r
134  * </p>\r
135  *\r
136  * @author Robert Harder\r
137  * @author rob@iharder.net\r
138  * @version 2.3.3\r
139  */\r
140 public class Base64\r
141 {\r
142     \r
143 /* ********  P U B L I C   F I E L D S  ******** */   \r
144     \r
145     \r
146     /** No options specified. Value is zero. */\r
147     public final static int NO_OPTIONS = 0;\r
148     \r
149     /** Specify encoding in first bit. Value is one. */\r
150     public final static int ENCODE = 1;\r
151     \r
152     \r
153     /** Specify decoding in first bit. Value is zero. */\r
154     public final static int DECODE = 0;\r
155     \r
156 \r
157     /** Specify that data should be gzip-compressed in second bit. Value is two. */\r
158     public final static int GZIP = 2;\r
159 \r
160     /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */\r
161     public final static int DONT_GUNZIP = 4;\r
162     \r
163     \r
164     /** Do break lines when encoding. Value is 8. */\r
165     public final static int DO_BREAK_LINES = 8;\r
166         \r
167     /** \r
168      * Encode using Base64-like encoding that is URL- and Filename-safe as described\r
169      * in Section 4 of RFC3548: \r
170      * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.\r
171      * It is important to note that data encoded this way is <em>not</em> officially valid Base64, \r
172      * or at the very least should not be called Base64 without also specifying that is\r
173      * was encoded using the URL- and Filename-safe dialect.\r
174      */\r
175      public final static int URL_SAFE = 16;\r
176 \r
177 \r
178      /**\r
179       * Encode using the special "ordered" dialect of Base64 described here:\r
180       * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.\r
181       */\r
182      public final static int ORDERED = 32;\r
183     \r
184     \r
185 /* ********  P R I V A T E   F I E L D S  ******** */  \r
186     \r
187     \r
188     /** Maximum line length (76) of Base64 output. */\r
189     private final static int MAX_LINE_LENGTH = 76;\r
190     \r
191     \r
192     /** The equals sign (=) as a byte. */\r
193     private final static byte EQUALS_SIGN = (byte)'=';\r
194     \r
195     \r
196     /** The new line character (\n) as a byte. */\r
197     private final static byte NEW_LINE = (byte)'\n';\r
198     \r
199     \r
200     /** Preferred encoding. */\r
201     private final static String PREFERRED_ENCODING = "US-ASCII";\r
202     \r
203         \r
204     private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding\r
205     private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding\r
206         \r
207         \r
208 /* ********  S T A N D A R D   B A S E 6 4   A L P H A B E T  ******** */       \r
209     \r
210     /** The 64 valid Base64 values. */\r
211     /* Host platform me be something funny like EBCDIC, so we hardcode these values. */\r
212     private final static byte[] _STANDARD_ALPHABET = {\r
213         (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',\r
214         (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',\r
215         (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', \r
216         (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',\r
217         (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',\r
218         (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',\r
219         (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', \r
220         (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',\r
221         (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', \r
222         (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'\r
223     };\r
224         \r
225     \r
226     /** \r
227      * Translates a Base64 value to either its 6-bit reconstruction value\r
228      * or a negative number indicating some other meaning.\r
229      **/\r
230     private final static byte[] _STANDARD_DECODABET = {\r
231         -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8\r
232         -5,-5,                                      // Whitespace: Tab and Linefeed\r
233         -9,-9,                                      // Decimal 11 - 12\r
234         -5,                                         // Whitespace: Carriage Return\r
235         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26\r
236         -9,-9,-9,-9,-9,                             // Decimal 27 - 31\r
237         -5,                                         // Whitespace: Space\r
238         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42\r
239         62,                                         // Plus sign at decimal 43\r
240         -9,-9,-9,                                   // Decimal 44 - 46\r
241         63,                                         // Slash at decimal 47\r
242         52,53,54,55,56,57,58,59,60,61,              // Numbers zero through nine\r
243         -9,-9,-9,                                   // Decimal 58 - 60\r
244         -1,                                         // Equals sign at decimal 61\r
245         -9,-9,-9,                                      // Decimal 62 - 64\r
246         0,1,2,3,4,5,6,7,8,9,10,11,12,13,            // Letters 'A' through 'N'\r
247         14,15,16,17,18,19,20,21,22,23,24,25,        // Letters 'O' through 'Z'\r
248         -9,-9,-9,-9,-9,-9,                          // Decimal 91 - 96\r
249         26,27,28,29,30,31,32,33,34,35,36,37,38,     // Letters 'a' through 'm'\r
250         39,40,41,42,43,44,45,46,47,48,49,50,51,     // Letters 'n' through 'z'\r
251         -9,-9,-9,-9                                 // Decimal 123 - 126\r
252         /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 127 - 139\r
253         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152\r
254         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165\r
255         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178\r
256         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191\r
257         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204\r
258         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217\r
259         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230\r
260         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243\r
261         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255 */\r
262     };\r
263         \r
264         \r
265 /* ********  U R L   S A F E   B A S E 6 4   A L P H A B E T  ******** */\r
266         \r
267     /**\r
268      * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: \r
269      * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.\r
270      * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."\r
271      */\r
272     private final static byte[] _URL_SAFE_ALPHABET = {\r
273       (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',\r
274       (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',\r
275       (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', \r
276       (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',\r
277       (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',\r
278       (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',\r
279       (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', \r
280       (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',\r
281       (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', \r
282       (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'\r
283     };\r
284         \r
285     /**\r
286      * Used in decoding URL- and Filename-safe dialects of Base64.\r
287      */\r
288     private final static byte[] _URL_SAFE_DECODABET = {\r
289       -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8\r
290       -5,-5,                                      // Whitespace: Tab and Linefeed\r
291       -9,-9,                                      // Decimal 11 - 12\r
292       -5,                                         // Whitespace: Carriage Return\r
293       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26\r
294       -9,-9,-9,-9,-9,                             // Decimal 27 - 31\r
295       -5,                                         // Whitespace: Space\r
296       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42\r
297       -9,                                         // Plus sign at decimal 43\r
298       -9,                                         // Decimal 44\r
299       62,                                         // Minus sign at decimal 45\r
300       -9,                                         // Decimal 46\r
301       -9,                                         // Slash at decimal 47\r
302       52,53,54,55,56,57,58,59,60,61,              // Numbers zero through nine\r
303       -9,-9,-9,                                   // Decimal 58 - 60\r
304       -1,                                         // Equals sign at decimal 61\r
305       -9,-9,-9,                                   // Decimal 62 - 64\r
306       0,1,2,3,4,5,6,7,8,9,10,11,12,13,            // Letters 'A' through 'N'\r
307       14,15,16,17,18,19,20,21,22,23,24,25,        // Letters 'O' through 'Z'\r
308       -9,-9,-9,-9,                                // Decimal 91 - 94\r
309       63,                                         // Underscore at decimal 95\r
310       -9,                                         // Decimal 96\r
311       26,27,28,29,30,31,32,33,34,35,36,37,38,     // Letters 'a' through 'm'\r
312       39,40,41,42,43,44,45,46,47,48,49,50,51,     // Letters 'n' through 'z'\r
313       -9,-9,-9,-9                                 // Decimal 123 - 126\r
314       /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 127 - 139\r
315       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152\r
316       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165\r
317       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178\r
318       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191\r
319       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204\r
320       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217\r
321       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230\r
322       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243\r
323       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255 */\r
324     };\r
325 \r
326 \r
327 \r
328 /* ********  O R D E R E D   B A S E 6 4   A L P H A B E T  ******** */\r
329 \r
330     /**\r
331      * I don't get the point of this technique, but someone requested it,\r
332      * and it is described here:\r
333      * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.\r
334      */\r
335     private final static byte[] _ORDERED_ALPHABET = {\r
336       (byte)'-',\r
337       (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',\r
338       (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',\r
339       (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',\r
340       (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',\r
341       (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',\r
342       (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',\r
343       (byte)'_',\r
344       (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',\r
345       (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',\r
346       (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',\r
347       (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'\r
348     };\r
349         \r
350     /**\r
351      * Used in decoding the "ordered" dialect of Base64.\r
352      */\r
353     private final static byte[] _ORDERED_DECODABET = {\r
354       -9,-9,-9,-9,-9,-9,-9,-9,-9,                 // Decimal  0 -  8\r
355       -5,-5,                                      // Whitespace: Tab and Linefeed\r
356       -9,-9,                                      // Decimal 11 - 12\r
357       -5,                                         // Whitespace: Carriage Return\r
358       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 14 - 26\r
359       -9,-9,-9,-9,-9,                             // Decimal 27 - 31\r
360       -5,                                         // Whitespace: Space\r
361       -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,              // Decimal 33 - 42\r
362       -9,                                         // Plus sign at decimal 43\r
363       -9,                                         // Decimal 44\r
364       0,                                          // Minus sign at decimal 45\r
365       -9,                                         // Decimal 46\r
366       -9,                                         // Slash at decimal 47\r
367       1,2,3,4,5,6,7,8,9,10,                       // Numbers zero through nine\r
368       -9,-9,-9,                                   // Decimal 58 - 60\r
369       -1,                                         // Equals sign at decimal 61\r
370       -9,-9,-9,                                   // Decimal 62 - 64\r
371       11,12,13,14,15,16,17,18,19,20,21,22,23,     // Letters 'A' through 'M'\r
372       24,25,26,27,28,29,30,31,32,33,34,35,36,     // Letters 'N' through 'Z'\r
373       -9,-9,-9,-9,                                // Decimal 91 - 94\r
374       37,                                         // Underscore at decimal 95\r
375       -9,                                         // Decimal 96\r
376       38,39,40,41,42,43,44,45,46,47,48,49,50,     // Letters 'a' through 'm'\r
377       51,52,53,54,55,56,57,58,59,60,61,62,63,     // Letters 'n' through 'z'\r
378       -9,-9,-9,-9                                 // Decimal 123 - 126\r
379       /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 127 - 139\r
380         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 140 - 152\r
381         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 153 - 165\r
382         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 166 - 178\r
383         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 179 - 191\r
384         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 192 - 204\r
385         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 205 - 217\r
386         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 218 - 230\r
387         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,     // Decimal 231 - 243\r
388         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9         // Decimal 244 - 255 */\r
389     };\r
390 \r
391         \r
392 /* ********  D E T E R M I N E   W H I C H   A L H A B E T  ******** */\r
393 \r
394 \r
395     /**\r
396      * Returns one of the _SOMETHING_ALPHABET byte arrays depending on\r
397      * the options specified.\r
398      * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE\r
399      * in which case one of them will be picked, though there is\r
400      * no guarantee as to which one will be picked.\r
401      */\r
402     private final static byte[] getAlphabet( int options ) {\r
403         if ((options & URL_SAFE) == URL_SAFE) {\r
404             return _URL_SAFE_ALPHABET;\r
405         } else if ((options & ORDERED) == ORDERED) {\r
406             return _ORDERED_ALPHABET;\r
407         } else {\r
408             return _STANDARD_ALPHABET;\r
409         }\r
410     }   // end getAlphabet\r
411 \r
412 \r
413     /**\r
414      * Returns one of the _SOMETHING_DECODABET byte arrays depending on\r
415      * the options specified.\r
416      * It's possible, though silly, to specify ORDERED and URL_SAFE\r
417      * in which case one of them will be picked, though there is\r
418      * no guarantee as to which one will be picked.\r
419      */\r
420     private final static byte[] getDecodabet( int options ) {\r
421         if( (options & URL_SAFE) == URL_SAFE) {\r
422             return _URL_SAFE_DECODABET;\r
423         } else if ((options & ORDERED) == ORDERED) {\r
424             return _ORDERED_DECODABET;\r
425         } else {\r
426             return _STANDARD_DECODABET;\r
427         }\r
428     }   // end getAlphabet\r
429 \r
430 \r
431     \r
432     /** Defeats instantiation. */\r
433     Base64(){}\r
434     \r
435 \r
436     \r
437     \r
438 /* ********  E N C O D I N G   M E T H O D S  ******** */    \r
439     \r
440     \r
441     /**\r
442      * Encodes up to the first three bytes of array <var>threeBytes</var>\r
443      * and returns a four-byte array in Base64 notation.\r
444      * The actual number of significant bytes in your array is\r
445      * given by <var>numSigBytes</var>.\r
446      * The array <var>threeBytes</var> needs only be as big as\r
447      * <var>numSigBytes</var>.\r
448      * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.\r
449      *\r
450      * @param b4 A reusable byte array to reduce array instantiation\r
451      * @param threeBytes the array to convert\r
452      * @param numSigBytes the number of significant bytes in your array\r
453      * @return four byte array in Base64 notation.\r
454      * @since 1.5.1\r
455      */\r
456     private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {\r
457         encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );\r
458         return b4;\r
459     }   // end encode3to4\r
460 \r
461     \r
462     /**\r
463      * <p>Encodes up to three bytes of the array <var>source</var>\r
464      * and writes the resulting four Base64 bytes to <var>destination</var>.\r
465      * The source and destination arrays can be manipulated\r
466      * anywhere along their length by specifying \r
467      * <var>srcOffset</var> and <var>destOffset</var>.\r
468      * This method does not check to make sure your arrays\r
469      * are large enough to accomodate <var>srcOffset</var> + 3 for\r
470      * the <var>source</var> array or <var>destOffset</var> + 4 for\r
471      * the <var>destination</var> array.\r
472      * The actual number of significant bytes in your array is\r
473      * given by <var>numSigBytes</var>.</p>\r
474          * <p>This is the lowest level of the encoding methods with\r
475          * all possible parameters.</p>\r
476      *\r
477      * @param source the array to convert\r
478      * @param srcOffset the index where conversion begins\r
479      * @param numSigBytes the number of significant bytes in your array\r
480      * @param destination the array to hold the conversion\r
481      * @param destOffset the index where output will be put\r
482      * @return the <var>destination</var> array\r
483      * @since 1.3\r
484      */\r
485     private static byte[] encode3to4( \r
486     byte[] source, int srcOffset, int numSigBytes,\r
487     byte[] destination, int destOffset, int options ) {\r
488         \r
489         byte[] ALPHABET = getAlphabet( options ); \r
490         \r
491         //           1         2         3  \r
492         // 01234567890123456789012345678901 Bit position\r
493         // --------000000001111111122222222 Array position from threeBytes\r
494         // --------|    ||    ||    ||    | Six bit groups to index ALPHABET\r
495         //          >>18  >>12  >> 6  >> 0  Right shift necessary\r
496         //                0x3f  0x3f  0x3f  Additional AND\r
497         \r
498         // Create buffer with zero-padding if there are only one or two\r
499         // significant bytes passed in the array.\r
500         // We have to shift left 24 in order to flush out the 1's that appear\r
501         // when Java treats a value as negative that is cast from a byte to an int.\r
502         int inBuff =   ( numSigBytes > 0 ? ((source[ srcOffset     ] << 24) >>>  8) : 0 )\r
503                      | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )\r
504                      | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );\r
505 \r
506         switch( numSigBytes )\r
507         {\r
508             case 3:\r
509                 destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];\r
510                 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];\r
511                 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>>  6) & 0x3f ];\r
512                 destination[ destOffset + 3 ] = ALPHABET[ (inBuff       ) & 0x3f ];\r
513                 return destination;\r
514                 \r
515             case 2:\r
516                 destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];\r
517                 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];\r
518                 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>>  6) & 0x3f ];\r
519                 destination[ destOffset + 3 ] = EQUALS_SIGN;\r
520                 return destination;\r
521                 \r
522             case 1:\r
523                 destination[ destOffset     ] = ALPHABET[ (inBuff >>> 18)        ];\r
524                 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];\r
525                 destination[ destOffset + 2 ] = EQUALS_SIGN;\r
526                 destination[ destOffset + 3 ] = EQUALS_SIGN;\r
527                 return destination;\r
528                 \r
529             default:\r
530                 return destination;\r
531         }   // end switch\r
532     }   // end encode3to4\r
533 \r
534 \r
535 \r
536     /**\r
537      * Performs Base64 encoding on the <code>raw</code> ByteBuffer,\r
538      * writing it to the <code>encoded</code> ByteBuffer.\r
539      * This is an experimental feature. Currently it does not\r
540      * pass along any options (such as {@link #DO_BREAK_LINES}\r
541      * or {@link #GZIP}.\r
542      *\r
543      * @param raw input buffer\r
544      * @param encoded output buffer\r
545      * @since 2.3\r
546      */\r
547     public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){\r
548         byte[] raw3 = new byte[3];\r
549         byte[] enc4 = new byte[4];\r
550 \r
551         while( raw.hasRemaining() ){\r
552             int rem = Math.min(3,raw.remaining());\r
553             raw.get(raw3,0,rem);\r
554             Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );\r
555             encoded.put(enc4);\r
556         }   // end input remaining\r
557     }\r
558 \r
559 \r
560     /**\r
561      * Performs Base64 encoding on the <code>raw</code> ByteBuffer,\r
562      * writing it to the <code>encoded</code> CharBuffer.\r
563      * This is an experimental feature. Currently it does not\r
564      * pass along any options (such as {@link #DO_BREAK_LINES}\r
565      * or {@link #GZIP}.\r
566      *\r
567      * @param raw input buffer\r
568      * @param encoded output buffer\r
569      * @since 2.3\r
570      */\r
571     public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){\r
572         byte[] raw3 = new byte[3];\r
573         byte[] enc4 = new byte[4];\r
574 \r
575         while( raw.hasRemaining() ){\r
576             int rem = Math.min(3,raw.remaining());\r
577             raw.get(raw3,0,rem);\r
578             Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );\r
579             for( int i = 0; i < 4; i++ ){\r
580                 encoded.put( (char)(enc4[i] & 0xFF) );\r
581             }\r
582         }   // end input remaining\r
583     }\r
584 \r
585 \r
586     \r
587     \r
588     /**\r
589      * Serializes an object and returns the Base64-encoded\r
590      * version of that serialized object.  \r
591      *  \r
592      * <p>As of v 2.3, if the object\r
593      * cannot be serialized or there is another error,\r
594      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
595      * In earlier versions, it just returned a null value, but\r
596      * in retrospect that's a pretty poor way to handle it.</p>\r
597      * \r
598      * The object is not GZip-compressed before being encoded.\r
599      *\r
600      * @param serializableObject The object to encode\r
601      * @return The Base64-encoded object\r
602      * @throws java.io.IOException if there is an error\r
603      * @throws NullPointerException if serializedObject is null\r
604      * @since 1.4\r
605      */\r
606     public static String encodeObject( java.io.Serializable serializableObject )\r
607     throws java.io.IOException {\r
608         return encodeObject( serializableObject, NO_OPTIONS );\r
609     }   // end encodeObject\r
610     \r
611 \r
612 \r
613     /**\r
614      * Serializes an object and returns the Base64-encoded\r
615      * version of that serialized object.\r
616      *  \r
617      * <p>As of v 2.3, if the object\r
618      * cannot be serialized or there is another error,\r
619      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
620      * In earlier versions, it just returned a null value, but\r
621      * in retrospect that's a pretty poor way to handle it.</p>\r
622      * \r
623      * The object is not GZip-compressed before being encoded.\r
624      * <p>\r
625      * Example options:<pre>\r
626      *   GZIP: gzip-compresses object before encoding it.\r
627      *   DO_BREAK_LINES: break lines at 76 characters\r
628      * </pre>\r
629      * <p>\r
630      * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or\r
631      * <p>\r
632      * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>\r
633      *\r
634      * @param serializableObject The object to encode\r
635      * @param options Specified options\r
636      * @return The Base64-encoded object\r
637      * @see Base64#GZIP\r
638      * @see Base64#DO_BREAK_LINES\r
639      * @throws java.io.IOException if there is an error\r
640      * @since 2.0\r
641      */\r
642     public static String encodeObject( java.io.Serializable serializableObject, int options )\r
643     throws java.io.IOException {\r
644 \r
645         if( serializableObject == null ){\r
646             throw new NullPointerException( "Cannot serialize a null object." );\r
647         }   // end if: null\r
648         \r
649         // Streams\r
650         java.io.ByteArrayOutputStream  baos  = null; \r
651         java.io.OutputStream           b64os = null;\r
652         java.util.zip.GZIPOutputStream gzos  = null;\r
653         java.io.ObjectOutputStream     oos   = null;\r
654         \r
655         \r
656         try {\r
657             // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream\r
658             baos  = new java.io.ByteArrayOutputStream();\r
659             b64os = new Base64.OutputStream( baos, ENCODE | options );\r
660             if( (options & GZIP) != 0 ){\r
661                 // Gzip\r
662                 gzos = new java.util.zip.GZIPOutputStream(b64os);\r
663                 oos = new java.io.ObjectOutputStream( gzos );\r
664             } else {\r
665                 // Not gzipped\r
666                 oos = new java.io.ObjectOutputStream( b64os );\r
667             }\r
668             oos.writeObject( serializableObject );\r
669         }   // end try\r
670         catch( java.io.IOException e ) {\r
671             // Catch it and then throw it immediately so that\r
672             // the finally{} block is called for cleanup.\r
673             throw e;\r
674         }   // end catch\r
675         finally {\r
676             try{ oos.close();   } catch( Exception e ){}\r
677             try{ gzos.close();  } catch( Exception e ){}\r
678             try{ b64os.close(); } catch( Exception e ){}\r
679             try{ baos.close();  } catch( Exception e ){}\r
680         }   // end finally\r
681         \r
682         // Return value according to relevant encoding.\r
683         try {\r
684             return new String( baos.toByteArray(), PREFERRED_ENCODING );\r
685         }   // end try\r
686         catch (java.io.UnsupportedEncodingException uue){\r
687             // Fall back to some Java default\r
688             return new String( baos.toByteArray() );\r
689         }   // end catch\r
690         \r
691     }   // end encode\r
692     \r
693     \r
694 \r
695     /**\r
696      * Encodes a byte array into Base64 notation.\r
697      * Does not GZip-compress data.\r
698      *  \r
699      * @param source The data to convert\r
700      * @return The data in Base64-encoded form\r
701      * @throws NullPointerException if source array is null\r
702      * @since 1.4\r
703      */\r
704     public static String encodeBytes( byte[] source ) {\r
705         // Since we're not going to have the GZIP encoding turned on,\r
706         // we're not going to have an java.io.IOException thrown, so\r
707         // we should not force the user to have to catch it.\r
708         String encoded = null;\r
709         try {\r
710             encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);\r
711         } catch (java.io.IOException ex) {\r
712             assert false : ex.getMessage();\r
713         }   // end catch\r
714         assert encoded != null;\r
715         return encoded;\r
716     }   // end encodeBytes\r
717     \r
718 \r
719 \r
720     /**\r
721      * Encodes a byte array into Base64 notation.\r
722      * <p>\r
723      * Example options:<pre>\r
724      *   GZIP: gzip-compresses object before encoding it.\r
725      *   DO_BREAK_LINES: break lines at 76 characters\r
726      *     <i>Note: Technically, this makes your encoding non-compliant.</i>\r
727      * </pre>\r
728      * <p>\r
729      * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or\r
730      * <p>\r
731      * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>\r
732      *\r
733      *  \r
734      * <p>As of v 2.3, if there is an error with the GZIP stream,\r
735      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
736      * In earlier versions, it just returned a null value, but\r
737      * in retrospect that's a pretty poor way to handle it.</p>\r
738      * \r
739      *\r
740      * @param source The data to convert\r
741      * @param options Specified options\r
742      * @return The Base64-encoded data as a String\r
743      * @see Base64#GZIP\r
744      * @see Base64#DO_BREAK_LINES\r
745      * @throws java.io.IOException if there is an error\r
746      * @throws NullPointerException if source array is null\r
747      * @since 2.0\r
748      */\r
749     public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {\r
750         return encodeBytes( source, 0, source.length, options );\r
751     }   // end encodeBytes\r
752     \r
753     \r
754     /**\r
755      * Encodes a byte array into Base64 notation.\r
756      * Does not GZip-compress data.\r
757      *  \r
758      * <p>As of v 2.3, if there is an error,\r
759      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
760      * In earlier versions, it just returned a null value, but\r
761      * in retrospect that's a pretty poor way to handle it.</p>\r
762      * \r
763      *\r
764      * @param source The data to convert\r
765      * @param off Offset in array where conversion should begin\r
766      * @param len Length of data to convert\r
767      * @return The Base64-encoded data as a String\r
768      * @throws NullPointerException if source array is null\r
769      * @throws IllegalArgumentException if source array, offset, or length are invalid\r
770      * @since 1.4\r
771      */\r
772     public static String encodeBytes( byte[] source, int off, int len ) {\r
773         // Since we're not going to have the GZIP encoding turned on,\r
774         // we're not going to have an java.io.IOException thrown, so\r
775         // we should not force the user to have to catch it.\r
776         String encoded = null;\r
777         try {\r
778             encoded = encodeBytes( source, off, len, NO_OPTIONS );\r
779         } catch (java.io.IOException ex) {\r
780             assert false : ex.getMessage();\r
781         }   // end catch\r
782         assert encoded != null;\r
783         return encoded;\r
784     }   // end encodeBytes\r
785     \r
786     \r
787 \r
788     /**\r
789      * Encodes a byte array into Base64 notation.\r
790      * <p>\r
791      * Example options:<pre>\r
792      *   GZIP: gzip-compresses object before encoding it.\r
793      *   DO_BREAK_LINES: break lines at 76 characters\r
794      *     <i>Note: Technically, this makes your encoding non-compliant.</i>\r
795      * </pre>\r
796      * <p>\r
797      * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or\r
798      * <p>\r
799      * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>\r
800      *\r
801      *  \r
802      * <p>As of v 2.3, if there is an error with the GZIP stream,\r
803      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
804      * In earlier versions, it just returned a null value, but\r
805      * in retrospect that's a pretty poor way to handle it.</p>\r
806      * \r
807      *\r
808      * @param source The data to convert\r
809      * @param off Offset in array where conversion should begin\r
810      * @param len Length of data to convert\r
811      * @param options Specified options\r
812      * @return The Base64-encoded data as a String\r
813      * @see Base64#GZIP\r
814      * @see Base64#DO_BREAK_LINES\r
815      * @throws java.io.IOException if there is an error\r
816      * @throws NullPointerException if source array is null\r
817      * @throws IllegalArgumentException if source array, offset, or length are invalid\r
818      * @since 2.0\r
819      */\r
820     public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {\r
821         byte[] encoded = encodeBytesToBytes( source, off, len, options );\r
822 \r
823         // Return value according to relevant encoding.\r
824         try {\r
825             return new String( encoded, PREFERRED_ENCODING );\r
826         }   // end try\r
827         catch (java.io.UnsupportedEncodingException uue) {\r
828             return new String( encoded );\r
829         }   // end catch\r
830         \r
831     }   // end encodeBytes\r
832 \r
833 \r
834 \r
835 \r
836     /**\r
837      * Similar to {@link #encodeBytes(byte[])} but returns\r
838      * a byte array instead of instantiating a String. This is more efficient\r
839      * if you're working with I/O streams and have large data sets to encode.\r
840      *\r
841      *\r
842      * @param source The data to convert\r
843      * @return The Base64-encoded data as a byte[] (of ASCII characters)\r
844      * @throws NullPointerException if source array is null\r
845      * @since 2.3.1\r
846      */\r
847     public static byte[] encodeBytesToBytes( byte[] source ) {\r
848         byte[] encoded = null;\r
849         try {\r
850             encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );\r
851         } catch( java.io.IOException ex ) {\r
852             assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();\r
853         }\r
854         return encoded;\r
855     }\r
856 \r
857 \r
858     /**\r
859      * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns\r
860      * a byte array instead of instantiating a String. This is more efficient\r
861      * if you're working with I/O streams and have large data sets to encode.\r
862      *\r
863      *\r
864      * @param source The data to convert\r
865      * @param off Offset in array where conversion should begin\r
866      * @param len Length of data to convert\r
867      * @param options Specified options\r
868      * @return The Base64-encoded data as a String\r
869      * @see Base64#GZIP\r
870      * @see Base64#DO_BREAK_LINES\r
871      * @throws java.io.IOException if there is an error\r
872      * @throws NullPointerException if source array is null\r
873      * @throws IllegalArgumentException if source array, offset, or length are invalid\r
874      * @since 2.3.1\r
875      */\r
876     public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {\r
877 \r
878         if( source == null ){\r
879             throw new NullPointerException( "Cannot serialize a null array." );\r
880         }   // end if: null\r
881 \r
882         if( off < 0 ){\r
883             throw new IllegalArgumentException( "Cannot have negative offset: " + off );\r
884         }   // end if: off < 0\r
885 \r
886         if( len < 0 ){\r
887             throw new IllegalArgumentException( "Cannot have length offset: " + len );\r
888         }   // end if: len < 0\r
889 \r
890         if( off + len > source.length  ){\r
891             throw new IllegalArgumentException(\r
892             String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));\r
893         }   // end if: off < 0\r
894 \r
895 \r
896 \r
897         // Compress?\r
898         if( (options & GZIP) != 0 ) {\r
899             java.io.ByteArrayOutputStream  baos  = null;\r
900             java.util.zip.GZIPOutputStream gzos  = null;\r
901             Base64.OutputStream            b64os = null;\r
902 \r
903             try {\r
904                 // GZip -> Base64 -> ByteArray\r
905                 baos = new java.io.ByteArrayOutputStream();\r
906                 b64os = new Base64.OutputStream( baos, ENCODE | options );\r
907                 gzos  = new java.util.zip.GZIPOutputStream( b64os );\r
908 \r
909                 gzos.write( source, off, len );\r
910                 gzos.close();\r
911             }   // end try\r
912             catch( java.io.IOException e ) {\r
913                 // Catch it and then throw it immediately so that\r
914                 // the finally{} block is called for cleanup.\r
915                 throw e;\r
916             }   // end catch\r
917             finally {\r
918                 try{ gzos.close();  } catch( Exception e ){}\r
919                 try{ b64os.close(); } catch( Exception e ){}\r
920                 try{ baos.close();  } catch( Exception e ){}\r
921             }   // end finally\r
922 \r
923             return baos.toByteArray();\r
924         }   // end if: compress\r
925 \r
926         // Else, don't compress. Better not to use streams at all then.\r
927         else {\r
928             boolean breakLines = (options & DO_BREAK_LINES) > 0;\r
929 \r
930             //int    len43   = len * 4 / 3;\r
931             //byte[] outBuff = new byte[   ( len43 )                      // Main 4:3\r
932             //                           + ( (len % 3) > 0 ? 4 : 0 )      // Account for padding\r
933             //                           + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines\r
934             // Try to determine more precisely how big the array needs to be.\r
935             // If we get it right, we don't have to do an array copy, and\r
936             // we save a bunch of memory.\r
937             int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding\r
938             if( breakLines ){\r
939                 encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters\r
940             }\r
941             byte[] outBuff = new byte[ encLen ];\r
942 \r
943 \r
944             int d = 0;\r
945             int e = 0;\r
946             int len2 = len - 2;\r
947             int lineLength = 0;\r
948             for( ; d < len2; d+=3, e+=4 ) {\r
949                 encode3to4( source, d+off, 3, outBuff, e, options );\r
950 \r
951                 lineLength += 4;\r
952                 if( breakLines && lineLength >= MAX_LINE_LENGTH )\r
953                 {\r
954                     outBuff[e+4] = NEW_LINE;\r
955                     e++;\r
956                     lineLength = 0;\r
957                 }   // end if: end of line\r
958             }   // en dfor: each piece of array\r
959 \r
960             if( d < len ) {\r
961                 encode3to4( source, d+off, len - d, outBuff, e, options );\r
962                 e += 4;\r
963             }   // end if: some padding needed\r
964 \r
965 \r
966             // Only resize array if we didn't guess it right.\r
967             if( e < outBuff.length - 1 ){\r
968                 byte[] finalOut = new byte[e];\r
969                 System.arraycopy(outBuff,0, finalOut,0,e);\r
970                 //System.err.println("Having to resize array from " + outBuff.length + " to " + e );\r
971                 return finalOut;\r
972             } else {\r
973                 //System.err.println("No need to resize array.");\r
974                 return outBuff;\r
975             }\r
976         \r
977         }   // end else: don't compress\r
978 \r
979     }   // end encodeBytesToBytes\r
980     \r
981 \r
982     \r
983     \r
984     \r
985 /* ********  D E C O D I N G   M E T H O D S  ******** */\r
986     \r
987     \r
988     /**\r
989      * Decodes four bytes from array <var>source</var>\r
990      * and writes the resulting bytes (up to three of them)\r
991      * to <var>destination</var>.\r
992      * The source and destination arrays can be manipulated\r
993      * anywhere along their length by specifying \r
994      * <var>srcOffset</var> and <var>destOffset</var>.\r
995      * This method does not check to make sure your arrays\r
996      * are large enough to accomodate <var>srcOffset</var> + 4 for\r
997      * the <var>source</var> array or <var>destOffset</var> + 3 for\r
998      * the <var>destination</var> array.\r
999      * This method returns the actual number of bytes that \r
1000      * were converted from the Base64 encoding.\r
1001          * <p>This is the lowest level of the decoding methods with\r
1002          * all possible parameters.</p>\r
1003      * \r
1004      *\r
1005      * @param source the array to convert\r
1006      * @param srcOffset the index where conversion begins\r
1007      * @param destination the array to hold the conversion\r
1008      * @param destOffset the index where output will be put\r
1009          * @param options alphabet type is pulled from this (standard, url-safe, ordered)\r
1010      * @return the number of decoded bytes converted\r
1011      * @throws NullPointerException if source or destination arrays are null\r
1012      * @throws IllegalArgumentException if srcOffset or destOffset are invalid\r
1013      *         or there is not enough room in the array.\r
1014      * @since 1.3\r
1015      */\r
1016     private static int decode4to3( \r
1017     byte[] source, int srcOffset, \r
1018     byte[] destination, int destOffset, int options ) {\r
1019         \r
1020         // Lots of error checking and exception throwing\r
1021         if( source == null ){\r
1022             throw new NullPointerException( "Source array was null." );\r
1023         }   // end if\r
1024         if( destination == null ){\r
1025             throw new NullPointerException( "Destination array was null." );\r
1026         }   // end if\r
1027         if( srcOffset < 0 || srcOffset + 3 >= source.length ){\r
1028             throw new IllegalArgumentException( String.format(\r
1029             "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );\r
1030         }   // end if\r
1031         if( destOffset < 0 || destOffset +2 >= destination.length ){\r
1032             throw new IllegalArgumentException( String.format(\r
1033             "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );\r
1034         }   // end if\r
1035         \r
1036         \r
1037         byte[] DECODABET = getDecodabet( options ); \r
1038         \r
1039         // Example: Dk==\r
1040         if( source[ srcOffset + 2] == EQUALS_SIGN ) {\r
1041             // Two ways to do the same thing. Don't know which way I like best.\r
1042           //int outBuff =   ( ( DECODABET[ source[ srcOffset    ] ] << 24 ) >>>  6 )\r
1043           //              | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );\r
1044             int outBuff =   ( ( DECODABET[ source[ srcOffset    ] ] & 0xFF ) << 18 )\r
1045                           | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );\r
1046             \r
1047             destination[ destOffset ] = (byte)( outBuff >>> 16 );\r
1048             return 1;\r
1049         }\r
1050         \r
1051         // Example: DkL=\r
1052         else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {\r
1053             // Two ways to do the same thing. Don't know which way I like best.\r
1054           //int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] << 24 ) >>>  6 )\r
1055           //              | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )\r
1056           //              | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );\r
1057             int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] & 0xFF ) << 18 )\r
1058                           | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )\r
1059                           | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) <<  6 );\r
1060             \r
1061             destination[ destOffset     ] = (byte)( outBuff >>> 16 );\r
1062             destination[ destOffset + 1 ] = (byte)( outBuff >>>  8 );\r
1063             return 2;\r
1064         }\r
1065         \r
1066         // Example: DkLE\r
1067         else {\r
1068             // Two ways to do the same thing. Don't know which way I like best.\r
1069           //int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] << 24 ) >>>  6 )\r
1070           //              | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )\r
1071           //              | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )\r
1072           //              | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );\r
1073             int outBuff =   ( ( DECODABET[ source[ srcOffset     ] ] & 0xFF ) << 18 )\r
1074                           | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )\r
1075                           | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) <<  6)\r
1076                           | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF )      );\r
1077 \r
1078             \r
1079             destination[ destOffset     ] = (byte)( outBuff >> 16 );\r
1080             destination[ destOffset + 1 ] = (byte)( outBuff >>  8 );\r
1081             destination[ destOffset + 2 ] = (byte)( outBuff       );\r
1082 \r
1083             return 3;\r
1084         }\r
1085     }   // end decodeToBytes\r
1086     \r
1087 \r
1088 \r
1089 \r
1090 \r
1091     /**\r
1092      * Low-level access to decoding ASCII characters in\r
1093      * the form of a byte array. <strong>Ignores GUNZIP option, if\r
1094      * it's set.</strong> This is not generally a recommended method,\r
1095      * although it is used internally as part of the decoding process.\r
1096      * Special case: if len = 0, an empty array is returned. Still,\r
1097      * if you need more speed and reduced memory footprint (and aren't\r
1098      * gzipping), consider this method.\r
1099      *\r
1100      * @param source The Base64 encoded data\r
1101      * @return decoded data\r
1102      * @since 2.3.1\r
1103      */\r
1104     public static byte[] decode( byte[] source ){\r
1105         byte[] decoded = null;\r
1106         try {\r
1107             decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );\r
1108         } catch( java.io.IOException ex ) {\r
1109             assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();\r
1110         }\r
1111         return decoded;\r
1112     }\r
1113 \r
1114     \r
1115     \r
1116     /**\r
1117      * Low-level access to decoding ASCII characters in\r
1118      * the form of a byte array. <strong>Ignores GUNZIP option, if\r
1119      * it's set.</strong> This is not generally a recommended method,\r
1120      * although it is used internally as part of the decoding process.\r
1121      * Special case: if len = 0, an empty array is returned. Still,\r
1122      * if you need more speed and reduced memory footprint (and aren't\r
1123      * gzipping), consider this method.\r
1124      *\r
1125      * @param source The Base64 encoded data\r
1126      * @param off    The offset of where to begin decoding\r
1127      * @param len    The length of characters to decode\r
1128      * @param options Can specify options such as alphabet type to use\r
1129      * @return decoded data\r
1130      * @throws java.io.IOException If bogus characters exist in source data\r
1131      * @since 1.3\r
1132      */\r
1133     public static byte[] decode( byte[] source, int off, int len, int options )\r
1134     throws java.io.IOException {\r
1135         \r
1136         // Lots of error checking and exception throwing\r
1137         if( source == null ){\r
1138             throw new NullPointerException( "Cannot decode null source array." );\r
1139         }   // end if\r
1140         if( off < 0 || off + len > source.length ){\r
1141             throw new IllegalArgumentException( String.format(\r
1142             "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );\r
1143         }   // end if\r
1144         \r
1145         if( len == 0 ){\r
1146             return new byte[0];\r
1147         }else if( len < 4 ){\r
1148             throw new IllegalArgumentException( \r
1149             "Base64-encoded string must have at least four characters, but length specified was " + len );\r
1150         }   // end if\r
1151         \r
1152         byte[] DECODABET = getDecodabet( options );\r
1153         \r
1154         int    len34   = len * 3 / 4;       // Estimate on array size\r
1155         byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output\r
1156         int    outBuffPosn = 0;             // Keep track of where we're writing\r
1157         \r
1158         byte[] b4        = new byte[4];     // Four byte buffer from source, eliminating white space\r
1159         int    b4Posn    = 0;               // Keep track of four byte input buffer\r
1160         int    i         = 0;               // Source array counter\r
1161         byte   sbiCrop   = 0;               // Low seven bits (ASCII) of input\r
1162         byte   sbiDecode = 0;               // Special value from DECODABET\r
1163         \r
1164         for( i = off; i < off+len; i++ ) {  // Loop through source\r
1165             \r
1166             sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits\r
1167             sbiDecode = DECODABET[ sbiCrop ];   // Special value\r
1168             \r
1169             // White space, Equals sign, or legit Base64 character\r
1170             // Note the values such as -5 and -9 in the\r
1171             // DECODABETs at the top of the file.\r
1172             if( sbiDecode >= WHITE_SPACE_ENC )  {\r
1173                 if( sbiDecode >= EQUALS_SIGN_ENC ) {\r
1174                     b4[ b4Posn++ ] = sbiCrop;           // Save non-whitespace\r
1175                     if( b4Posn > 3 ) {                  // Time to decode?\r
1176                         outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );\r
1177                         b4Posn = 0;\r
1178                         \r
1179                         // If that was the equals sign, break out of 'for' loop\r
1180                         if( sbiCrop == EQUALS_SIGN ) {\r
1181                             break;\r
1182                         }   // end if: equals sign\r
1183                     }   // end if: quartet built\r
1184                 }   // end if: equals sign or better\r
1185             }   // end if: white space, equals sign or better\r
1186             else {\r
1187                 // There's a bad input character in the Base64 stream.\r
1188                 throw new java.io.IOException( String.format(\r
1189                 "Bad Base64 input character '%c' in array position %d", source[i], i ) );\r
1190             }   // end else: \r
1191         }   // each input character\r
1192                                    \r
1193         byte[] out = new byte[ outBuffPosn ];\r
1194         System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); \r
1195         return out;\r
1196     }   // end decode\r
1197     \r
1198     \r
1199         \r
1200         \r
1201     /**\r
1202      * Decodes data from Base64 notation, automatically\r
1203      * detecting gzip-compressed data and decompressing it.\r
1204      *\r
1205      * @param s the string to decode\r
1206      * @return the decoded data\r
1207      * @throws java.io.IOException If there is a problem\r
1208      * @since 1.4\r
1209      */\r
1210     public static byte[] decode( String s ) throws java.io.IOException {\r
1211         return decode( s, NO_OPTIONS );\r
1212     }\r
1213 \r
1214     \r
1215     \r
1216     /**\r
1217      * Decodes data from Base64 notation, automatically\r
1218      * detecting gzip-compressed data and decompressing it.\r
1219      *\r
1220      * @param s the string to decode\r
1221      * @param options encode options such as URL_SAFE\r
1222      * @return the decoded data\r
1223      * @throws java.io.IOException if there is an error\r
1224      * @throws NullPointerException if <tt>s</tt> is null\r
1225      * @since 1.4\r
1226      */\r
1227     public static byte[] decode( String s, int options ) throws java.io.IOException {\r
1228         \r
1229         if( s == null ){\r
1230             throw new NullPointerException( "Input string was null." );\r
1231         }   // end if\r
1232         \r
1233         byte[] bytes;\r
1234         try {\r
1235             bytes = s.getBytes( PREFERRED_ENCODING );\r
1236         }   // end try\r
1237         catch( java.io.UnsupportedEncodingException uee ) {\r
1238             bytes = s.getBytes();\r
1239         }   // end catch\r
1240                 //</change>\r
1241         \r
1242         // Decode\r
1243         bytes = decode( bytes, 0, bytes.length, options );\r
1244         \r
1245         // Check to see if it's gzip-compressed\r
1246         // GZIP Magic Two-Byte Number: 0x8b1f (35615)\r
1247         boolean dontGunzip = (options & DONT_GUNZIP) != 0;\r
1248         if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {\r
1249             \r
1250             int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);\r
1251             if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )  {\r
1252                 java.io.ByteArrayInputStream  bais = null;\r
1253                 java.util.zip.GZIPInputStream gzis = null;\r
1254                 java.io.ByteArrayOutputStream baos = null;\r
1255                 byte[] buffer = new byte[2048];\r
1256                 int    length = 0;\r
1257 \r
1258                 try {\r
1259                     baos = new java.io.ByteArrayOutputStream();\r
1260                     bais = new java.io.ByteArrayInputStream( bytes );\r
1261                     gzis = new java.util.zip.GZIPInputStream( bais );\r
1262 \r
1263                     while( ( length = gzis.read( buffer ) ) >= 0 ) {\r
1264                         baos.write(buffer,0,length);\r
1265                     }   // end while: reading input\r
1266 \r
1267                     // No error? Get new bytes.\r
1268                     bytes = baos.toByteArray();\r
1269 \r
1270                 }   // end try\r
1271                 catch( java.io.IOException e ) {\r
1272                     e.printStackTrace();\r
1273                     // Just return originally-decoded bytes\r
1274                 }   // end catch\r
1275                 finally {\r
1276                     try{ baos.close(); } catch( Exception e ){}\r
1277                     try{ gzis.close(); } catch( Exception e ){}\r
1278                     try{ bais.close(); } catch( Exception e ){}\r
1279                 }   // end finally\r
1280 \r
1281             }   // end if: gzipped\r
1282         }   // end if: bytes.length >= 2\r
1283         \r
1284         return bytes;\r
1285     }   // end decode\r
1286 \r
1287 \r
1288 \r
1289     /**\r
1290      * Attempts to decode Base64 data and deserialize a Java\r
1291      * Object within. Returns <tt>null</tt> if there was an error.\r
1292      *\r
1293      * @param encodedObject The Base64 data to decode\r
1294      * @return The decoded and deserialized object\r
1295      * @throws NullPointerException if encodedObject is null\r
1296      * @throws java.io.IOException if there is a general error\r
1297      * @throws ClassNotFoundException if the decoded object is of a\r
1298      *         class that cannot be found by the JVM\r
1299      * @since 1.5\r
1300      */\r
1301     public static Object decodeToObject( String encodedObject )\r
1302     throws java.io.IOException, java.lang.ClassNotFoundException {\r
1303         return decodeToObject(encodedObject,NO_OPTIONS,null);\r
1304     }\r
1305     \r
1306 \r
1307     /**\r
1308      * Attempts to decode Base64 data and deserialize a Java\r
1309      * Object within. Returns <tt>null</tt> if there was an error.\r
1310      * If <tt>loader</tt> is not null, it will be the class loader\r
1311      * used when deserializing.\r
1312      *\r
1313      * @param encodedObject The Base64 data to decode\r
1314      * @param options Various parameters related to decoding\r
1315      * @param loader Optional class loader to use in deserializing classes.\r
1316      * @return The decoded and deserialized object\r
1317      * @throws NullPointerException if encodedObject is null\r
1318      * @throws java.io.IOException if there is a general error\r
1319      * @throws ClassNotFoundException if the decoded object is of a \r
1320      *         class that cannot be found by the JVM\r
1321      * @since 2.3.4\r
1322      */\r
1323     public static Object decodeToObject( \r
1324     String encodedObject, int options, final ClassLoader loader )\r
1325     throws java.io.IOException, java.lang.ClassNotFoundException {\r
1326         \r
1327         // Decode and gunzip if necessary\r
1328         byte[] objBytes = decode( encodedObject, options );\r
1329         \r
1330         java.io.ByteArrayInputStream  bais = null;\r
1331         java.io.ObjectInputStream     ois  = null;\r
1332         Object obj = null;\r
1333         \r
1334         try {\r
1335             bais = new java.io.ByteArrayInputStream( objBytes );\r
1336 \r
1337             // If no custom class loader is provided, use Java's builtin OIS.\r
1338             if( loader == null ){\r
1339                 ois  = new java.io.ObjectInputStream( bais );\r
1340             }   // end if: no loader provided\r
1341 \r
1342             // Else make a customized object input stream that uses\r
1343             // the provided class loader.\r
1344             else {\r
1345                 ois = new java.io.ObjectInputStream(bais){\r
1346                     @SuppressWarnings("unchecked")\r
1347                                         @Override\r
1348                     public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)\r
1349                     throws java.io.IOException, ClassNotFoundException {\r
1350                         Class c = Class.forName(streamClass.getName(), false, loader);\r
1351                         if( c == null ){\r
1352                             return super.resolveClass(streamClass);\r
1353                         } else {\r
1354                             return c;   // Class loader knows of this class.\r
1355                         }   // end else: not null\r
1356                     }   // end resolveClass\r
1357                 };  // end ois\r
1358             }   // end else: no custom class loader\r
1359         \r
1360             obj = ois.readObject();\r
1361         }   // end try\r
1362         catch( java.io.IOException e ) {\r
1363             throw e;    // Catch and throw in order to execute finally{}\r
1364         }   // end catch\r
1365         catch( java.lang.ClassNotFoundException e ) {\r
1366             throw e;    // Catch and throw in order to execute finally{}\r
1367         }   // end catch\r
1368         finally {\r
1369             try{ bais.close(); } catch( Exception e ){}\r
1370             try{ ois.close();  } catch( Exception e ){}\r
1371         }   // end finally\r
1372         \r
1373         return obj;\r
1374     }   // end decodeObject\r
1375     \r
1376     \r
1377     \r
1378     /**\r
1379      * Convenience method for encoding data to a file.\r
1380      *\r
1381      * <p>As of v 2.3, if there is a error,\r
1382      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
1383      * In earlier versions, it just returned false, but\r
1384      * in retrospect that's a pretty poor way to handle it.</p>\r
1385      * \r
1386      * @param dataToEncode byte array of data to encode in base64 form\r
1387      * @param filename Filename for saving encoded data\r
1388      * @throws java.io.IOException if there is an error\r
1389      * @throws NullPointerException if dataToEncode is null\r
1390      * @since 2.1\r
1391      */\r
1392     public static void encodeToFile( byte[] dataToEncode, String filename )\r
1393     throws java.io.IOException {\r
1394         \r
1395         if( dataToEncode == null ){\r
1396             throw new NullPointerException( "Data to encode was null." );\r
1397         }   // end iff\r
1398         \r
1399         Base64.OutputStream bos = null;\r
1400         try {\r
1401             bos = new Base64.OutputStream( \r
1402                   new java.io.FileOutputStream( filename ), Base64.ENCODE );\r
1403             bos.write( dataToEncode );\r
1404         }   // end try\r
1405         catch( java.io.IOException e ) {\r
1406             throw e; // Catch and throw to execute finally{} block\r
1407         }   // end catch: java.io.IOException\r
1408         finally {\r
1409             try{ bos.close(); } catch( Exception e ){}\r
1410         }   // end finally\r
1411         \r
1412     }   // end encodeToFile\r
1413     \r
1414     \r
1415     /**\r
1416      * Convenience method for decoding data to a file.\r
1417      *\r
1418      * <p>As of v 2.3, if there is a error,\r
1419      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
1420      * In earlier versions, it just returned false, but\r
1421      * in retrospect that's a pretty poor way to handle it.</p>\r
1422      * \r
1423      * @param dataToDecode Base64-encoded data as a string\r
1424      * @param filename Filename for saving decoded data\r
1425      * @throws java.io.IOException if there is an error\r
1426      * @since 2.1\r
1427      */\r
1428     public static void decodeToFile( String dataToDecode, String filename )\r
1429     throws java.io.IOException {\r
1430         \r
1431         Base64.OutputStream bos = null;\r
1432         try{\r
1433             bos = new Base64.OutputStream( \r
1434                       new java.io.FileOutputStream( filename ), Base64.DECODE );\r
1435             bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );\r
1436         }   // end try\r
1437         catch( java.io.IOException e ) {\r
1438             throw e; // Catch and throw to execute finally{} block\r
1439         }   // end catch: java.io.IOException\r
1440         finally {\r
1441                 try{ bos.close(); } catch( Exception e ){}\r
1442         }   // end finally\r
1443         \r
1444     }   // end decodeToFile\r
1445     \r
1446     \r
1447     \r
1448     \r
1449     /**\r
1450      * Convenience method for reading a base64-encoded\r
1451      * file and decoding it.\r
1452      *\r
1453      * <p>As of v 2.3, if there is a error,\r
1454      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
1455      * In earlier versions, it just returned false, but\r
1456      * in retrospect that's a pretty poor way to handle it.</p>\r
1457      * \r
1458      * @param filename Filename for reading encoded data\r
1459      * @return decoded byte array\r
1460      * @throws java.io.IOException if there is an error\r
1461      * @since 2.1\r
1462      */\r
1463     public static byte[] decodeFromFile( String filename )\r
1464     throws java.io.IOException {\r
1465         \r
1466         byte[] decodedData = null;\r
1467         Base64.InputStream bis = null;\r
1468         try\r
1469         {\r
1470             // Set up some useful variables\r
1471             java.io.File file = new java.io.File( filename );\r
1472             byte[] buffer = null;\r
1473             int length   = 0;\r
1474             int numBytes = 0;\r
1475             \r
1476             // Check for size of file\r
1477             if( file.length() > Integer.MAX_VALUE )\r
1478             {\r
1479                 throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );\r
1480             }   // end if: file too big for int index\r
1481             buffer = new byte[ (int)file.length() ];\r
1482             \r
1483             // Open a stream\r
1484             bis = new Base64.InputStream( \r
1485                       new java.io.BufferedInputStream( \r
1486                       new java.io.FileInputStream( file ) ), Base64.DECODE );\r
1487             \r
1488             // Read until done\r
1489             while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {\r
1490                 length += numBytes;\r
1491             }   // end while\r
1492             \r
1493             // Save in a variable to return\r
1494             decodedData = new byte[ length ];\r
1495             System.arraycopy( buffer, 0, decodedData, 0, length );\r
1496             \r
1497         }   // end try\r
1498         catch( java.io.IOException e ) {\r
1499             throw e; // Catch and release to execute finally{}\r
1500         }   // end catch: java.io.IOException\r
1501         finally {\r
1502             try{ bis.close(); } catch( Exception e) {}\r
1503         }   // end finally\r
1504         \r
1505         return decodedData;\r
1506     }   // end decodeFromFile\r
1507     \r
1508     \r
1509     \r
1510     /**\r
1511      * Convenience method for reading a binary file\r
1512      * and base64-encoding it.\r
1513      *\r
1514      * <p>As of v 2.3, if there is a error,\r
1515      * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\r
1516      * In earlier versions, it just returned false, but\r
1517      * in retrospect that's a pretty poor way to handle it.</p>\r
1518      * \r
1519      * @param filename Filename for reading binary data\r
1520      * @return base64-encoded string\r
1521      * @throws java.io.IOException if there is an error\r
1522      * @since 2.1\r
1523      */\r
1524     public static String encodeFromFile( String filename )\r
1525     throws java.io.IOException {\r
1526         \r
1527         String encodedData = null;\r
1528         Base64.InputStream bis = null;\r
1529         try\r
1530         {\r
1531             // Set up some useful variables\r
1532             java.io.File file = new java.io.File( filename );\r
1533             byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)\r
1534             int length   = 0;\r
1535             int numBytes = 0;\r
1536             \r
1537             // Open a stream\r
1538             bis = new Base64.InputStream( \r
1539                       new java.io.BufferedInputStream( \r
1540                       new java.io.FileInputStream( file ) ), Base64.ENCODE );\r
1541             \r
1542             // Read until done\r
1543             while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {\r
1544                 length += numBytes;\r
1545             }   // end while\r
1546             \r
1547             // Save in a variable to return\r
1548             encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );\r
1549                 \r
1550         }   // end try\r
1551         catch( java.io.IOException e ) {\r
1552             throw e; // Catch and release to execute finally{}\r
1553         }   // end catch: java.io.IOException\r
1554         finally {\r
1555             try{ bis.close(); } catch( Exception e) {}\r
1556         }   // end finally\r
1557         \r
1558         return encodedData;\r
1559         }   // end encodeFromFile\r
1560     \r
1561     /**\r
1562      * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.\r
1563      *\r
1564      * @param infile Input file\r
1565      * @param outfile Output file\r
1566      * @throws java.io.IOException if there is an error\r
1567      * @since 2.2\r
1568      */\r
1569     public static void encodeFileToFile( String infile, String outfile )\r
1570     throws java.io.IOException {\r
1571         \r
1572         String encoded = Base64.encodeFromFile( infile );\r
1573         java.io.OutputStream out = null;\r
1574         try{\r
1575             out = new java.io.BufferedOutputStream(\r
1576                   new java.io.FileOutputStream( outfile ) );\r
1577             out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.\r
1578         }   // end try\r
1579         catch( java.io.IOException e ) {\r
1580             throw e; // Catch and release to execute finally{}\r
1581         }   // end catch\r
1582         finally {\r
1583             try { out.close(); }\r
1584             catch( Exception ex ){}\r
1585         }   // end finally    \r
1586     }   // end encodeFileToFile\r
1587 \r
1588 \r
1589     /**\r
1590      * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.\r
1591      *\r
1592      * @param infile Input file\r
1593      * @param outfile Output file\r
1594      * @throws java.io.IOException if there is an error\r
1595      * @since 2.2\r
1596      */\r
1597     public static void decodeFileToFile( String infile, String outfile )\r
1598     throws java.io.IOException {\r
1599         \r
1600         byte[] decoded = Base64.decodeFromFile( infile );\r
1601         java.io.OutputStream out = null;\r
1602         try{\r
1603             out = new java.io.BufferedOutputStream(\r
1604                   new java.io.FileOutputStream( outfile ) );\r
1605             out.write( decoded );\r
1606         }   // end try\r
1607         catch( java.io.IOException e ) {\r
1608             throw e; // Catch and release to execute finally{}\r
1609         }   // end catch\r
1610         finally {\r
1611             try { out.close(); }\r
1612             catch( Exception ex ){}\r
1613         }   // end finally    \r
1614     }   // end decodeFileToFile\r
1615     \r
1616     \r
1617     /* ********  I N N E R   C L A S S   I N P U T S T R E A M  ******** */\r
1618     \r
1619     \r
1620     \r
1621     /**\r
1622      * A {@link Base64.InputStream} will read data from another\r
1623      * <tt>java.io.InputStream</tt>, given in the constructor,\r
1624      * and encode/decode to/from Base64 notation on the fly.\r
1625      *\r
1626      * @see Base64\r
1627      * @since 1.3\r
1628      */\r
1629     public static class InputStream extends java.io.FilterInputStream {\r
1630         \r
1631         private final boolean encode;         // Encoding or decoding\r
1632         private int     position;       // Current position in the buffer\r
1633         private final byte[]  buffer;         // Small buffer holding converted data\r
1634         private final int     bufferLength;   // Length of buffer (3 or 4)\r
1635         private int     numSigBytes;    // Number of meaningful bytes in the buffer\r
1636         private int     lineLength;\r
1637         private final boolean breakLines;     // Break lines at less than 80 characters\r
1638         private final int     options;        // Record options used to create the stream.\r
1639         private final byte[]  decodabet;      // Local copies to avoid extra method calls\r
1640         \r
1641         \r
1642         /**\r
1643          * Constructs a {@link Base64.InputStream} in DECODE mode.\r
1644          *\r
1645          * @param in the <tt>java.io.InputStream</tt> from which to read data.\r
1646          * @since 1.3\r
1647          */\r
1648         public InputStream( java.io.InputStream in ) {\r
1649             this( in, DECODE );\r
1650         }   // end constructor\r
1651         \r
1652         \r
1653         /**\r
1654          * Constructs a {@link Base64.InputStream} in\r
1655          * either ENCODE or DECODE mode.\r
1656          * <p>\r
1657          * Valid options:<pre>\r
1658          *   ENCODE or DECODE: Encode or Decode as data is read.\r
1659          *   DO_BREAK_LINES: break lines at 76 characters\r
1660          *     (only meaningful when encoding)</i>\r
1661          * </pre>\r
1662          * <p>\r
1663          * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>\r
1664          *\r
1665          *\r
1666          * @param in the <tt>java.io.InputStream</tt> from which to read data.\r
1667          * @param options Specified options\r
1668          * @see Base64#ENCODE\r
1669          * @see Base64#DECODE\r
1670          * @see Base64#DO_BREAK_LINES\r
1671          * @since 2.0\r
1672          */\r
1673         public InputStream( java.io.InputStream in, int options ) {\r
1674             \r
1675             super( in );\r
1676             this.options      = options; // Record for later\r
1677             this.breakLines   = (options & DO_BREAK_LINES) > 0;\r
1678             this.encode       = (options & ENCODE) > 0;\r
1679             this.bufferLength = encode ? 4 : 3;\r
1680             this.buffer       = new byte[ bufferLength ];\r
1681             this.position     = -1;\r
1682             this.lineLength   = 0;\r
1683             this.decodabet    = getDecodabet(options);\r
1684         }   // end constructor\r
1685         \r
1686         /**\r
1687          * Reads enough of the input stream to convert\r
1688          * to/from Base64 and returns the next byte.\r
1689          *\r
1690          * @return next byte\r
1691          * @since 1.3\r
1692          */\r
1693         @Override\r
1694         public int read() throws java.io.IOException  {\r
1695             \r
1696             // Do we need to get data?\r
1697             if( position < 0 ) {\r
1698                 if( encode ) {\r
1699                     byte[] b3 = new byte[3];\r
1700                     int numBinaryBytes = 0;\r
1701                     for( int i = 0; i < 3; i++ ) {\r
1702                         int b = in.read();\r
1703 \r
1704                         // If end of stream, b is -1.\r
1705                         if( b >= 0 ) {\r
1706                             b3[i] = (byte)b;\r
1707                             numBinaryBytes++;\r
1708                         } else {\r
1709                             break; // out of for loop\r
1710                         }   // end else: end of stream\r
1711                             \r
1712                     }   // end for: each needed input byte\r
1713                     \r
1714                     if( numBinaryBytes > 0 ) {\r
1715                         encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );\r
1716                         position = 0;\r
1717                         numSigBytes = 4;\r
1718                     }   // end if: got data\r
1719                     else {\r
1720                         return -1;  // Must be end of stream\r
1721                     }   // end else\r
1722                 }   // end if: encoding\r
1723                 \r
1724                 // Else decoding\r
1725                 else {\r
1726                     byte[] b4 = new byte[4];\r
1727                     int i = 0;\r
1728                     for( i = 0; i < 4; i++ ) {\r
1729                         // Read four "meaningful" bytes:\r
1730                         int b = 0;\r
1731                         do{ b = in.read(); }\r
1732                         while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );\r
1733                         \r
1734                         if( b < 0 ) {\r
1735                             break; // Reads a -1 if end of stream\r
1736                         }   // end if: end of stream\r
1737                         \r
1738                         b4[i] = (byte)b;\r
1739                     }   // end for: each needed input byte\r
1740                     \r
1741                     if( i == 4 ) {\r
1742                         numSigBytes = decode4to3( b4, 0, buffer, 0, options );\r
1743                         position = 0;\r
1744                     }   // end if: got four characters\r
1745                     else if( i == 0 ){\r
1746                         return -1;\r
1747                     }   // end else if: also padded correctly\r
1748                     else {\r
1749                         // Must have broken out from above.\r
1750                         throw new java.io.IOException( "Improperly padded Base64 input." );\r
1751                     }   // end \r
1752                     \r
1753                 }   // end else: decode\r
1754             }   // end else: get data\r
1755             \r
1756             // Got data?\r
1757             if( position >= 0 ) {\r
1758                 // End of relevant data?\r
1759                 if( /*!encode &&*/ position >= numSigBytes ){\r
1760                     return -1;\r
1761                 }   // end if: got data\r
1762                 \r
1763                 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {\r
1764                     lineLength = 0;\r
1765                     return '\n';\r
1766                 }   // end if\r
1767                 else {\r
1768                     lineLength++;   // This isn't important when decoding\r
1769                                     // but throwing an extra "if" seems\r
1770                                     // just as wasteful.\r
1771                     \r
1772                     int b = buffer[ position++ ];\r
1773 \r
1774                     if( position >= bufferLength ) {\r
1775                         position = -1;\r
1776                     }   // end if: end\r
1777 \r
1778                     return b & 0xFF; // This is how you "cast" a byte that's\r
1779                                      // intended to be unsigned.\r
1780                 }   // end else\r
1781             }   // end if: position >= 0\r
1782             \r
1783             // Else error\r
1784             else {\r
1785                 throw new java.io.IOException( "Error in Base64 code reading stream." );\r
1786             }   // end else\r
1787         }   // end read\r
1788         \r
1789         \r
1790         /**\r
1791          * Calls {@link #read()} repeatedly until the end of stream\r
1792          * is reached or <var>len</var> bytes are read.\r
1793          * Returns number of bytes read into array or -1 if\r
1794          * end of stream is encountered.\r
1795          *\r
1796          * @param dest array to hold values\r
1797          * @param off offset for array\r
1798          * @param len max number of bytes to read into array\r
1799          * @return bytes read into array or -1 if end of stream is encountered.\r
1800          * @since 1.3\r
1801          */\r
1802         @Override\r
1803         public int read( byte[] dest, int off, int len ) \r
1804         throws java.io.IOException {\r
1805             int i;\r
1806             int b;\r
1807             for( i = 0; i < len; i++ ) {\r
1808                 b = read();\r
1809                 \r
1810                 if( b >= 0 ) {\r
1811                     dest[off + i] = (byte) b;\r
1812                 }\r
1813                 else if( i == 0 ) {\r
1814                     return -1;\r
1815                 }\r
1816                 else {\r
1817                     break; // Out of 'for' loop\r
1818                 } // Out of 'for' loop\r
1819             }   // end for: each byte read\r
1820             return i;\r
1821         }   // end read\r
1822         \r
1823     }   // end inner class InputStream\r
1824     \r
1825     \r
1826     \r
1827     \r
1828     \r
1829     \r
1830     /* ********  I N N E R   C L A S S   O U T P U T S T R E A M  ******** */\r
1831     \r
1832     \r
1833     \r
1834     /**\r
1835      * A {@link Base64.OutputStream} will write data to another\r
1836      * <tt>java.io.OutputStream</tt>, given in the constructor,\r
1837      * and encode/decode to/from Base64 notation on the fly.\r
1838      *\r
1839      * @see Base64\r
1840      * @since 1.3\r
1841      */\r
1842     public static class OutputStream extends java.io.FilterOutputStream {\r
1843         \r
1844         private final boolean encode;\r
1845         private int     position;\r
1846         private byte[]  buffer;\r
1847         private final int     bufferLength;\r
1848         private int     lineLength;\r
1849         private final boolean breakLines;\r
1850         private final byte[]  b4;         // Scratch used in a few places\r
1851         private boolean suspendEncoding;\r
1852         private final int     options;    // Record for later\r
1853         private final byte[]  decodabet;  // Local copies to avoid extra method calls\r
1854         \r
1855         /**\r
1856          * Constructs a {@link Base64.OutputStream} in ENCODE mode.\r
1857          *\r
1858          * @param out the <tt>java.io.OutputStream</tt> to which data will be written.\r
1859          * @since 1.3\r
1860          */\r
1861         public OutputStream( java.io.OutputStream out ) {\r
1862             this( out, ENCODE );\r
1863         }   // end constructor\r
1864         \r
1865         \r
1866         /**\r
1867          * Constructs a {@link Base64.OutputStream} in\r
1868          * either ENCODE or DECODE mode.\r
1869          * <p>\r
1870          * Valid options:<pre>\r
1871          *   ENCODE or DECODE: Encode or Decode as data is read.\r
1872          *   DO_BREAK_LINES: don't break lines at 76 characters\r
1873          *     (only meaningful when encoding)</i>\r
1874          * </pre>\r
1875          * <p>\r
1876          * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>\r
1877          *\r
1878          * @param out the <tt>java.io.OutputStream</tt> to which data will be written.\r
1879          * @param options Specified options.\r
1880          * @see Base64#ENCODE\r
1881          * @see Base64#DECODE\r
1882          * @see Base64#DO_BREAK_LINES\r
1883          * @since 1.3\r
1884          */\r
1885         public OutputStream( java.io.OutputStream out, int options ) {\r
1886             super( out );\r
1887             this.breakLines   = (options & DO_BREAK_LINES) != 0;\r
1888             this.encode       = (options & ENCODE) != 0;\r
1889             this.bufferLength = encode ? 3 : 4;\r
1890             this.buffer       = new byte[ bufferLength ];\r
1891             this.position     = 0;\r
1892             this.lineLength   = 0;\r
1893             this.suspendEncoding = false;\r
1894             this.b4           = new byte[4];\r
1895             this.options      = options;\r
1896             this.decodabet    = getDecodabet(options);\r
1897         }   // end constructor\r
1898         \r
1899         \r
1900         /**\r
1901          * Writes the byte to the output stream after\r
1902          * converting to/from Base64 notation.\r
1903          * When encoding, bytes are buffered three\r
1904          * at a time before the output stream actually\r
1905          * gets a write() call.\r
1906          * When decoding, bytes are buffered four\r
1907          * at a time.\r
1908          *\r
1909          * @param theByte the byte to write\r
1910          * @since 1.3\r
1911          */\r
1912         @Override\r
1913         public void write(int theByte) \r
1914         throws java.io.IOException {\r
1915             // Encoding suspended?\r
1916             if( suspendEncoding ) {\r
1917                 this.out.write( theByte );\r
1918                 return;\r
1919             }   // end if: supsended\r
1920             \r
1921             // Encode?\r
1922             if( encode ) {\r
1923                 buffer[ position++ ] = (byte)theByte;\r
1924                 if( position >= bufferLength ) { // Enough to encode.\r
1925                 \r
1926                     this.out.write( encode3to4( b4, buffer, bufferLength, options ) );\r
1927 \r
1928                     lineLength += 4;\r
1929                     if( breakLines && lineLength >= MAX_LINE_LENGTH ) {\r
1930                         this.out.write( NEW_LINE );\r
1931                         lineLength = 0;\r
1932                     }   // end if: end of line\r
1933 \r
1934                     position = 0;\r
1935                 }   // end if: enough to output\r
1936             }   // end if: encoding\r
1937 \r
1938             // Else, Decoding\r
1939             else {\r
1940                 // Meaningful Base64 character?\r
1941                 if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {\r
1942                     buffer[ position++ ] = (byte)theByte;\r
1943                     if( position >= bufferLength ) { // Enough to output.\r
1944                     \r
1945                         int len = Base64.decode4to3( buffer, 0, b4, 0, options );\r
1946                         out.write( b4, 0, len );\r
1947                         position = 0;\r
1948                     }   // end if: enough to output\r
1949                 }   // end if: meaningful base64 character\r
1950                 else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {\r
1951                     throw new java.io.IOException( "Invalid character in Base64 data." );\r
1952                 }   // end else: not white space either\r
1953             }   // end else: decoding\r
1954         }   // end write\r
1955         \r
1956         \r
1957         \r
1958         /**\r
1959          * Calls {@link #write(int)} repeatedly until <var>len</var> \r
1960          * bytes are written.\r
1961          *\r
1962          * @param theBytes array from which to read bytes\r
1963          * @param off offset for array\r
1964          * @param len max number of bytes to read into array\r
1965          * @since 1.3\r
1966          */\r
1967         @Override\r
1968         public void write( byte[] theBytes, int off, int len ) \r
1969         throws java.io.IOException {\r
1970             // Encoding suspended?\r
1971             if( suspendEncoding ) {\r
1972                 this.out.write( theBytes, off, len );\r
1973                 return;\r
1974             }   // end if: supsended\r
1975             \r
1976             for( int i = 0; i < len; i++ ) {\r
1977                 write( theBytes[ off + i ] );\r
1978             }   // end for: each byte written\r
1979             \r
1980         }   // end write\r
1981         \r
1982         \r
1983         \r
1984         /**\r
1985          * Method added by PHIL. [Thanks, PHIL. -Rob]\r
1986          * This pads the buffer without closing the stream.\r
1987          * @throws java.io.IOException  if there's an error.\r
1988          */\r
1989         public void flushBase64() throws java.io.IOException  {\r
1990             if( position > 0 ) {\r
1991                 if( encode ) {\r
1992                     out.write( encode3to4( b4, buffer, position, options ) );\r
1993                     position = 0;\r
1994                 }   // end if: encoding\r
1995                 else {\r
1996                     throw new java.io.IOException( "Base64 input not properly padded." );\r
1997                 }   // end else: decoding\r
1998             }   // end if: buffer partially full\r
1999 \r
2000         }   // end flush\r
2001 \r
2002         \r
2003         /** \r
2004          * Flushes and closes (I think, in the superclass) the stream. \r
2005          *\r
2006          * @since 1.3\r
2007          */\r
2008         @Override\r
2009         public void close() throws java.io.IOException {\r
2010             // 1. Ensure that pending characters are written\r
2011             flushBase64();\r
2012 \r
2013             // 2. Actually close the stream\r
2014             // Base class both flushes and closes.\r
2015             super.close();\r
2016             \r
2017             buffer = null;\r
2018             out    = null;\r
2019         }   // end close\r
2020         \r
2021         \r
2022         \r
2023         /**\r
2024          * Suspends encoding of the stream.\r
2025          * May be helpful if you need to embed a piece of\r
2026          * base64-encoded data in a stream.\r
2027          *\r
2028          * @throws java.io.IOException  if there's an error flushing\r
2029          * @since 1.5.1\r
2030          */\r
2031         public void suspendEncoding() throws java.io.IOException  {\r
2032             flushBase64();\r
2033             this.suspendEncoding = true;\r
2034         }   // end suspendEncoding\r
2035         \r
2036         \r
2037         /**\r
2038          * Resumes encoding of the stream.\r
2039          * May be helpful if you need to embed a piece of\r
2040          * base64-encoded data in a stream.\r
2041          *\r
2042          * @since 1.5.1\r
2043          */\r
2044         public void resumeEncoding() {\r
2045             this.suspendEncoding = false;\r
2046         }   // end resumeEncoding\r
2047         \r
2048         \r
2049         \r
2050     }   // end inner class OutputStream\r
2051     \r
2052     \r
2053 }   // end class Base64\r