Debian Codegraph @

net/sourceforge/iharder/base64/Base64.java

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