/[aagtl_public1]/src/com/zoffcc/applications/aagtl/Base64.java
aagtl

Contents of /src/com/zoffcc/applications/aagtl/Base64.java

Parent Directory Parent Directory | Revision Log Revision Log


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

   
Visit the aagtl Website