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