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>
9 * <code>String encoded = Base64.encode( myByteArray );</code>
11 * <code>byte[] myByteArray = Base64.decode( encoded );</code>
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>
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>
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>
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>
30 * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
38 * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
39 * the Base64.OutputStream closed the Base64 encoding (by padding with equals
40 * signs) too soon. Also added an option to suppress the automatic decoding
41 * of gzipped streams. Also added experimental support for specifying a
42 * class loader when using the
43 * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
45 * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
46 * footprint with its CharEncoders and so forth. Fixed some javadocs that were
47 * inconsistent. Removed imports and specified things like java.io.IOException
48 * explicitly inline.</li>
49 * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
50 * final encoded data will be so that the code doesn't have to create two output
51 * arrays: an oversized initial one and then a final, exact-sized one. Big win
52 * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
53 * using the gzip options which uses a different mechanism with streams and stuff).</li>
54 * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
55 * similar helper methods to be more efficient with memory by not returning a
56 * String but just a byte array.</li>
57 * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
58 * and bug fixes queued up and finally executed. Thanks to everyone who sent
59 * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
60 * Much bad coding was cleaned up including throwing exceptions where necessary
61 * instead of returning null values or something similar. Here are some changes
62 * that may affect you:
64 * <li><em>Does not break lines, by default.</em> This is to keep in compliance with
65 * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
66 * <li><em>Throws exceptions instead of returning null values.</em> Because some operations
67 * (especially those that may permit the GZIP option) use IO streams, there
68 * is a possiblity of an java.io.IOException being thrown. After some discussion and
69 * thought, I've changed the behavior of the methods to throw java.io.IOExceptions
70 * rather than return null if ever there's an error. I think this is more
71 * appropriate, though it will require some changes to your code. Sorry,
72 * it should have been done this way to begin with.</li>
73 * <li><em>Removed all references to System.out, System.err, and the like.</em>
74 * Shame on me. All I can say is sorry they were ever there.</li>
75 * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
76 * such as when passed arrays are null or offsets are invalid.</li>
77 * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
78 * This was especially annoying before for people who were thorough in their
79 * own projects and then had gobs of javadoc warnings on this file.</li>
81 * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
82 * when using very small files (~< 40 bytes).</li>
83 * <li>v2.2 - Added some helper methods for encoding/decoding directly from
84 * one file to the next. Also added a main() method to support command line
85 * encoding/decoding from one file to the next. Also added these Base64 dialects:
87 * <li>The default is RFC3548 format.</li>
88 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
89 * URL and file name friendly format as described in Section 4 of RFC3548.
90 * http://www.faqs.org/rfcs/rfc3548.html</li>
91 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
92 * URL and file name friendly format that preserves lexical ordering as described
93 * in http://www.faqs.org/qa/rfcc-1940.html</li>
95 * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
96 * for contributing the new Base64 dialects.
99 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
100 * some convenience methods for reading and writing to and from files.</li>
101 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
102 * with other encodings (like EBCDIC).</li>
103 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
104 * encoded data was a single byte.</li>
105 * <li>v2.0 - I got rid of methods that used booleans to set options.
106 * Now everything is more consolidated and cleaner. The code now detects
107 * when data that's being decoded is gzip-compressed and will decompress it
108 * automatically. Generally things are cleaner. You'll probably have to
109 * change some method calls that you were making to support the new
110 * options format (<tt>int</tt>s that you "OR" together).</li>
111 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
112 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
113 * Added the ability to "suspend" encoding in the Output Stream so
114 * you can turn on and off the encoding if you need to embed base64
115 * data in an otherwise "normal" stream (like an XML file).</li>
116 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
117 * This helps when using GZIP streams.
118 * Added the ability to GZip-compress objects before encoding them.</li>
119 * <li>v1.4 - Added helper methods to read/write files.</li>
120 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
121 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
122 * where last buffer being read, if not completely full, was not returned.</li>
123 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
124 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
128 * I am placing this code in the Public Domain. Do with it as you will.
129 * This software comes with no guarantees or warranties but with
130 * plenty of well-wishing instead!
131 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
132 * periodically to check for updates or to contribute improvements.
135 * @author Robert Harder
136 * @author rob@iharder.net
139 public class Base64
{
141 /* ******** P U B L I C F I E L D S ******** */
145 * No options specified. Value is zero.
147 public final static int NO_OPTIONS
= 0;
150 * Specify encoding in first bit. Value is one.
152 public final static int ENCODE
= 1;
156 * Specify decoding in first bit. Value is zero.
158 public final static int DECODE
= 0;
162 * Specify that data should be gzip-compressed in second bit. Value is two.
164 public final static int GZIP
= 2;
167 * Specify that gzipped data should <em>not</em> be automatically gunzipped.
169 public final static int DONT_GUNZIP
= 4;
173 * Do break lines when encoding. Value is 8.
175 public final static int DO_BREAK_LINES
= 8;
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.
185 public final static int URL_SAFE
= 16;
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>.
192 public final static int ORDERED
= 32;
195 /* ******** P R I V A T E F I E L D S ******** */
199 * Maximum line length (76) of Base64 output.
201 private final static int MAX_LINE_LENGTH
= 76;
205 * The equals sign (=) as a byte.
207 private final static byte EQUALS_SIGN
= (byte) '=';
211 * The new line character (\n) as a byte.
213 private final static byte NEW_LINE
= (byte) '\n';
217 * Preferred encoding.
219 private final static String PREFERRED_ENCODING
= "US-ASCII";
222 private final static byte WHITE_SPACE_ENC
= -5; // Indicates white space in encoding
223 private final static byte EQUALS_SIGN_ENC
= -1; // Indicates equals sign in encoding
226 /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
229 * The 64 valid Base64 values.
231 /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
232 private final static byte[] _STANDARD_ALPHABET
= {
233 (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
234 (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
235 (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
236 (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
237 (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',
238 (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
239 (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
240 (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
241 (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',
242 (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'
247 * Translates a Base64 value to either its 6-bit reconstruction value
248 * or a negative number indicating some other meaning.
250 private final static byte[] _STANDARD_DECODABET
= {
251 -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
252 -5, -5, // Whitespace: Tab and Linefeed
253 -9, -9, // Decimal 11 - 12
254 -5, // Whitespace: Carriage Return
255 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
256 -9, -9, -9, -9, -9, // Decimal 27 - 31
257 -5, // Whitespace: Space
258 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
259 62, // Plus sign at decimal 43
260 -9, -9, -9, // Decimal 44 - 46
261 63, // Slash at decimal 47
262 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
263 -9, -9, -9, // Decimal 58 - 60
264 -1, // Equals sign at decimal 61
265 -9, -9, -9, // Decimal 62 - 64
266 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
267 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
268 -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
269 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
270 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
271 -9, -9, -9, -9 // Decimal 123 - 126
272 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
273 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
274 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
275 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
276 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
277 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
278 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
279 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
280 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
281 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
285 /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
288 * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
289 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
290 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
292 private final static byte[] _URL_SAFE_ALPHABET
= {
293 (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
294 (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
295 (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
296 (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
297 (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',
298 (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
299 (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
300 (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
301 (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',
302 (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'
306 * Used in decoding URL- and Filename-safe dialects of Base64.
308 private final static byte[] _URL_SAFE_DECODABET
= {
309 -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
310 -5, -5, // Whitespace: Tab and Linefeed
311 -9, -9, // Decimal 11 - 12
312 -5, // Whitespace: Carriage Return
313 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
314 -9, -9, -9, -9, -9, // Decimal 27 - 31
315 -5, // Whitespace: Space
316 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
317 -9, // Plus sign at decimal 43
319 62, // Minus sign at decimal 45
321 -9, // Slash at decimal 47
322 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
323 -9, -9, -9, // Decimal 58 - 60
324 -1, // Equals sign at decimal 61
325 -9, -9, -9, // Decimal 62 - 64
326 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
327 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
328 -9, -9, -9, -9, // Decimal 91 - 94
329 63, // Underscore at decimal 95
331 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
332 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
333 -9, -9, -9, -9 // Decimal 123 - 126
334 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
335 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
336 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
337 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
338 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
339 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
340 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
341 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
342 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
343 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
348 /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
351 * I don't get the point of this technique, but someone requested it,
352 * and it is described here:
353 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
355 private final static byte[] _ORDERED_ALPHABET
= {
357 (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
358 (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
359 (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
360 (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
361 (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
362 (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
364 (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',
365 (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
366 (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
367 (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z'
371 * Used in decoding the "ordered" dialect of Base64.
373 private final static byte[] _ORDERED_DECODABET
= {
374 -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
375 -5, -5, // Whitespace: Tab and Linefeed
376 -9, -9, // Decimal 11 - 12
377 -5, // Whitespace: Carriage Return
378 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
379 -9, -9, -9, -9, -9, // Decimal 27 - 31
380 -5, // Whitespace: Space
381 -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
382 -9, // Plus sign at decimal 43
384 0, // Minus sign at decimal 45
386 -9, // Slash at decimal 47
387 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine
388 -9, -9, -9, // Decimal 58 - 60
389 -1, // Equals sign at decimal 61
390 -9, -9, -9, // Decimal 62 - 64
391 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M'
392 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z'
393 -9, -9, -9, -9, // Decimal 91 - 94
394 37, // Underscore at decimal 95
396 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm'
397 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z'
398 -9, -9, -9, -9 // Decimal 123 - 126
399 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
400 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
401 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
402 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
403 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
404 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
405 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
406 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
407 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
408 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
412 /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
416 * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
417 * the options specified.
418 * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
419 * in which case one of them will be picked, though there is
420 * no guarantee as to which one will be picked.
422 private final static byte[] getAlphabet(int options
) {
423 if ((options
& URL_SAFE
) == URL_SAFE
) {
424 return _URL_SAFE_ALPHABET
;
425 } else if ((options
& ORDERED
) == ORDERED
) {
426 return _ORDERED_ALPHABET
;
428 return _STANDARD_ALPHABET
;
434 * Returns one of the _SOMETHING_DECODABET byte arrays depending on
435 * the options specified.
436 * It's possible, though silly, to specify ORDERED and URL_SAFE
437 * in which case one of them will be picked, though there is
438 * no guarantee as to which one will be picked.
440 private final static byte[] getDecodabet(int options
) {
441 if ((options
& URL_SAFE
) == URL_SAFE
) {
442 return _URL_SAFE_DECODABET
;
443 } else if ((options
& ORDERED
) == ORDERED
) {
444 return _ORDERED_DECODABET
;
446 return _STANDARD_DECODABET
;
452 * Defeats instantiation.
458 public static int getEncodedLengthWithoutPadding(int unencodedLength
) {
459 int remainderBytes
= unencodedLength
% 3;
460 int paddingBytes
= 0;
462 if (remainderBytes
!= 0)
463 paddingBytes
= 3 - remainderBytes
;
465 return (((int) ((unencodedLength
+ 2) / 3)) * 4) - paddingBytes
;
468 public static int getEncodedBytesForTarget(int targetSize
) {
469 return ((int) (targetSize
* 3)) / 4;
473 /* ******** E N C O D I N G M E T H O D S ******** */
477 * Encodes up to the first three bytes of array <var>threeBytes</var>
478 * and returns a four-byte array in Base64 notation.
479 * The actual number of significant bytes in your array is
480 * given by <var>numSigBytes</var>.
481 * The array <var>threeBytes</var> needs only be as big as
482 * <var>numSigBytes</var>.
483 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
485 * @param b4 A reusable byte array to reduce array instantiation
486 * @param threeBytes the array to convert
487 * @param numSigBytes the number of significant bytes in your array
488 * @return four byte array in Base64 notation.
491 private static byte[] encode3to4(byte[] b4
, byte[] threeBytes
, int numSigBytes
, int options
) {
492 encode3to4(threeBytes
, 0, numSigBytes
, b4
, 0, options
);
498 * <p>Encodes up to three bytes of the array <var>source</var>
499 * and writes the resulting four Base64 bytes to <var>destination</var>.
500 * The source and destination arrays can be manipulated
501 * anywhere along their length by specifying
502 * <var>srcOffset</var> and <var>destOffset</var>.
503 * This method does not check to make sure your arrays
504 * are large enough to accomodate <var>srcOffset</var> + 3 for
505 * the <var>source</var> array or <var>destOffset</var> + 4 for
506 * the <var>destination</var> array.
507 * The actual number of significant bytes in your array is
508 * given by <var>numSigBytes</var>.</p>
509 * <p>This is the lowest level of the encoding methods with
510 * all possible parameters.</p>
512 * @param source the array to convert
513 * @param srcOffset the index where conversion begins
514 * @param numSigBytes the number of significant bytes in your array
515 * @param destination the array to hold the conversion
516 * @param destOffset the index where output will be put
517 * @return the <var>destination</var> array
520 private static byte[] encode3to4(
521 byte[] source
, int srcOffset
, int numSigBytes
,
522 byte[] destination
, int destOffset
, int options
) {
524 byte[] ALPHABET
= getAlphabet(options
);
527 // 01234567890123456789012345678901 Bit position
528 // --------000000001111111122222222 Array position from threeBytes
529 // --------| || || || | Six bit groups to index ALPHABET
530 // >>18 >>12 >> 6 >> 0 Right shift necessary
531 // 0x3f 0x3f 0x3f Additional AND
533 // Create buffer with zero-padding if there are only one or two
534 // significant bytes passed in the array.
535 // We have to shift left 24 in order to flush out the 1's that appear
536 // when Java treats a value as negative that is cast from a byte to an int.
537 int inBuff
= (numSigBytes
> 0 ?
((source
[srcOffset
] << 24) >>> 8) : 0)
538 | (numSigBytes
> 1 ?
((source
[srcOffset
+ 1] << 24) >>> 16) : 0)
539 | (numSigBytes
> 2 ?
((source
[srcOffset
+ 2] << 24) >>> 24) : 0);
541 switch (numSigBytes
) {
543 destination
[destOffset
] = ALPHABET
[(inBuff
>>> 18)];
544 destination
[destOffset
+ 1] = ALPHABET
[(inBuff
>>> 12) & 0x3f];
545 destination
[destOffset
+ 2] = ALPHABET
[(inBuff
>>> 6) & 0x3f];
546 destination
[destOffset
+ 3] = ALPHABET
[(inBuff
) & 0x3f];
550 destination
[destOffset
] = ALPHABET
[(inBuff
>>> 18)];
551 destination
[destOffset
+ 1] = ALPHABET
[(inBuff
>>> 12) & 0x3f];
552 destination
[destOffset
+ 2] = ALPHABET
[(inBuff
>>> 6) & 0x3f];
553 destination
[destOffset
+ 3] = EQUALS_SIGN
;
557 destination
[destOffset
] = ALPHABET
[(inBuff
>>> 18)];
558 destination
[destOffset
+ 1] = ALPHABET
[(inBuff
>>> 12) & 0x3f];
559 destination
[destOffset
+ 2] = EQUALS_SIGN
;
560 destination
[destOffset
+ 3] = EQUALS_SIGN
;
570 * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
571 * writing it to the <code>encoded</code> ByteBuffer.
572 * This is an experimental feature. Currently it does not
573 * pass along any options (such as {@link #DO_BREAK_LINES}
576 * @param raw input buffer
577 * @param encoded output buffer
580 public static void encode(java
.nio
.ByteBuffer raw
, java
.nio
.ByteBuffer encoded
) {
581 byte[] raw3
= new byte[3];
582 byte[] enc4
= new byte[4];
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
);
589 } // end input remaining
594 * Performs Base64 encoding on the <code>raw</code> ByteBuffer,
595 * writing it to the <code>encoded</code> CharBuffer.
596 * This is an experimental feature. Currently it does not
597 * pass along any options (such as {@link #DO_BREAK_LINES}
600 * @param raw input buffer
601 * @param encoded output buffer
604 public static void encode(java
.nio
.ByteBuffer raw
, java
.nio
.CharBuffer encoded
) {
605 byte[] raw3
= new byte[3];
606 byte[] enc4
= new byte[4];
608 while (raw
.hasRemaining()) {
609 int rem
= Math
.min(3, raw
.remaining());
610 raw
.get(raw3
, 0, rem
);
611 Base64
.encode3to4(enc4
, raw3
, rem
, Base64
.NO_OPTIONS
);
612 for (int i
= 0; i
< 4; i
++) {
613 encoded
.put((char) (enc4
[i
] & 0xFF));
615 } // end input remaining
620 * Serializes an object and returns the Base64-encoded
621 * version of that serialized object.
623 * <p>As of v 2.3, if the object
624 * cannot be serialized or there is another error,
625 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
626 * In earlier versions, it just returned a null value, but
627 * in retrospect that's a pretty poor way to handle it.</p>
629 * The object is not GZip-compressed before being encoded.
631 * @param serializableObject The object to encode
632 * @return The Base64-encoded object
633 * @throws java.io.IOException if there is an error
634 * @throws NullPointerException if serializedObject is null
637 public static String
encodeObject(java
.io
.Serializable serializableObject
)
638 throws java
.io
.IOException
{
639 return encodeObject(serializableObject
, NO_OPTIONS
);
640 } // end encodeObject
644 * Serializes an object and returns the Base64-encoded
645 * version of that serialized object.
647 * <p>As of v 2.3, if the object
648 * cannot be serialized or there is another error,
649 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
650 * In earlier versions, it just returned a null value, but
651 * in retrospect that's a pretty poor way to handle it.</p>
653 * The object is not GZip-compressed before being encoded.
655 * Example options:<pre>
656 * GZIP: gzip-compresses object before encoding it.
657 * DO_BREAK_LINES: break lines at 76 characters
660 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
662 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
664 * @param serializableObject The object to encode
665 * @param options Specified options
666 * @return The Base64-encoded object
667 * @throws java.io.IOException if there is an error
669 * @see Base64#DO_BREAK_LINES
672 public static String
encodeObject(java
.io
.Serializable serializableObject
, int options
)
673 throws java
.io
.IOException
{
675 if (serializableObject
== null) {
676 throw new NullPointerException("Cannot serialize a null object.");
680 java
.io
.ByteArrayOutputStream baos
= null;
681 java
.io
.OutputStream b64os
= null;
682 java
.util
.zip
.GZIPOutputStream gzos
= null;
683 java
.io
.ObjectOutputStream oos
= null;
687 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
688 baos
= new java
.io
.ByteArrayOutputStream();
689 b64os
= new Base64
.OutputStream(baos
, ENCODE
| options
);
690 if ((options
& GZIP
) != 0) {
692 gzos
= new java
.util
.zip
.GZIPOutputStream(b64os
);
693 oos
= new java
.io
.ObjectOutputStream(gzos
);
696 oos
= new java
.io
.ObjectOutputStream(b64os
);
698 oos
.writeObject(serializableObject
);
700 catch (java
.io
.IOException e
) {
701 // Catch it and then throw it immediately so that
702 // the finally{} block is called for cleanup.
708 } catch (Exception e
) {
712 } catch (Exception e
) {
716 } catch (Exception e
) {
720 } catch (Exception e
) {
724 // Return value according to relevant encoding.
726 return new String(baos
.toByteArray(), PREFERRED_ENCODING
);
728 catch (java
.io
.UnsupportedEncodingException uue
) {
729 // Fall back to some Java default
730 return new String(baos
.toByteArray());
737 * Encodes a byte array into Base64 notation.
738 * Does not GZip-compress data.
740 * @param source The data to convert
741 * @return The data in Base64-encoded form
742 * @throws NullPointerException if source array is null
745 public static String
encodeBytes(byte[] source
) {
746 // Since we're not going to have the GZIP encoding turned on,
747 // we're not going to have an java.io.IOException thrown, so
748 // we should not force the user to have to catch it.
749 String encoded
= null;
751 encoded
= encodeBytes(source
, 0, source
.length
, NO_OPTIONS
);
752 } catch (java
.io
.IOException ex
) {
753 assert false : ex
.getMessage();
755 assert encoded
!= null;
760 public static String
encodeBytesWithoutPadding(byte[] source
, int offset
, int length
) {
761 String encoded
= null;
764 encoded
= encodeBytes(source
, offset
, length
, NO_OPTIONS
);
765 } catch (java
.io
.IOException ex
) {
766 assert false : ex
.getMessage();
769 assert encoded
!= null;
771 if (encoded
.charAt(encoded
.length() - 2) == '=')
772 return encoded
.substring(0, encoded
.length() - 2);
773 else if (encoded
.charAt(encoded
.length() - 1) == '=')
774 return encoded
.substring(0, encoded
.length() - 1);
779 public static String
encodeBytesWithoutPadding(byte[] source
) {
780 return encodeBytesWithoutPadding(source
, 0, source
.length
);
785 * Encodes a byte array into Base64 notation.
787 * Example options:<pre>
788 * GZIP: gzip-compresses object before encoding it.
789 * DO_BREAK_LINES: break lines at 76 characters
790 * <i>Note: Technically, this makes your encoding non-compliant.</i>
793 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
795 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
798 * <p>As of v 2.3, if there is an error with the GZIP stream,
799 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
800 * In earlier versions, it just returned a null value, but
801 * in retrospect that's a pretty poor way to handle it.</p>
803 * @param source The data to convert
804 * @param options Specified options
805 * @return The Base64-encoded data as a String
806 * @throws java.io.IOException if there is an error
807 * @throws NullPointerException if source array is null
809 * @see Base64#DO_BREAK_LINES
812 public static String
encodeBytes(byte[] source
, int options
) throws java
.io
.IOException
{
813 return encodeBytes(source
, 0, source
.length
, options
);
818 * Encodes a byte array into Base64 notation.
819 * Does not GZip-compress data.
821 * <p>As of v 2.3, if there is an error,
822 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
823 * In earlier versions, it just returned a null value, but
824 * in retrospect that's a pretty poor way to handle it.</p>
826 * @param source The data to convert
827 * @param off Offset in array where conversion should begin
828 * @param len Length of data to convert
829 * @return The Base64-encoded data as a String
830 * @throws NullPointerException if source array is null
831 * @throws IllegalArgumentException if source array, offset, or length are invalid
834 public static String
encodeBytes(byte[] source
, int off
, int len
) {
835 // Since we're not going to have the GZIP encoding turned on,
836 // we're not going to have an java.io.IOException thrown, so
837 // we should not force the user to have to catch it.
838 String encoded
= null;
840 encoded
= encodeBytes(source
, off
, len
, NO_OPTIONS
);
841 } catch (java
.io
.IOException ex
) {
842 assert false : ex
.getMessage();
844 assert encoded
!= null;
850 * Encodes a byte array into Base64 notation.
852 * Example options:<pre>
853 * GZIP: gzip-compresses object before encoding it.
854 * DO_BREAK_LINES: break lines at 76 characters
855 * <i>Note: Technically, this makes your encoding non-compliant.</i>
858 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
860 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
863 * <p>As of v 2.3, if there is an error with the GZIP stream,
864 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
865 * In earlier versions, it just returned a null value, but
866 * in retrospect that's a pretty poor way to handle it.</p>
868 * @param source The data to convert
869 * @param off Offset in array where conversion should begin
870 * @param len Length of data to convert
871 * @param options Specified options
872 * @return The Base64-encoded data as a String
873 * @throws java.io.IOException if there is an error
874 * @throws NullPointerException if source array is null
875 * @throws IllegalArgumentException if source array, offset, or length are invalid
877 * @see Base64#DO_BREAK_LINES
880 public static String
encodeBytes(byte[] source
, int off
, int len
, int options
) throws java
.io
.IOException
{
881 byte[] encoded
= encodeBytesToBytes(source
, off
, len
, options
);
883 // Return value according to relevant encoding.
885 return new String(encoded
, PREFERRED_ENCODING
);
887 catch (java
.io
.UnsupportedEncodingException uue
) {
888 return new String(encoded
);
895 * Similar to {@link #encodeBytes(byte[])} but returns
896 * a byte array instead of instantiating a String. This is more efficient
897 * if you're working with I/O streams and have large data sets to encode.
899 * @param source The data to convert
900 * @return The Base64-encoded data as a byte[] (of ASCII characters)
901 * @throws NullPointerException if source array is null
904 public static byte[] encodeBytesToBytes(byte[] source
) {
905 byte[] encoded
= null;
907 encoded
= encodeBytesToBytes(source
, 0, source
.length
, Base64
.NO_OPTIONS
);
908 } catch (java
.io
.IOException ex
) {
909 assert false : "IOExceptions only come from GZipping, which is turned off: " + ex
.getMessage();
916 * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
917 * a byte array instead of instantiating a String. This is more efficient
918 * if you're working with I/O streams and have large data sets to encode.
920 * @param source The data to convert
921 * @param off Offset in array where conversion should begin
922 * @param len Length of data to convert
923 * @param options Specified options
924 * @return The Base64-encoded data as a String
925 * @throws java.io.IOException if there is an error
926 * @throws NullPointerException if source array is null
927 * @throws IllegalArgumentException if source array, offset, or length are invalid
929 * @see Base64#DO_BREAK_LINES
932 public static byte[] encodeBytesToBytes(byte[] source
, int off
, int len
, int options
) throws java
.io
.IOException
{
934 if (source
== null) {
935 throw new NullPointerException("Cannot serialize a null array.");
939 throw new IllegalArgumentException("Cannot have negative offset: " + off
);
943 throw new IllegalArgumentException("Cannot have length offset: " + len
);
946 if (off
+ len
> source
.length
) {
947 throw new IllegalArgumentException(
948 String
.format("Cannot have offset of %d and length of %d with array of length %d", off
, len
, source
.length
));
953 if ((options
& GZIP
) != 0) {
954 java
.io
.ByteArrayOutputStream baos
= null;
955 java
.util
.zip
.GZIPOutputStream gzos
= null;
956 Base64
.OutputStream b64os
= null;
959 // GZip -> Base64 -> ByteArray
960 baos
= new java
.io
.ByteArrayOutputStream();
961 b64os
= new Base64
.OutputStream(baos
, ENCODE
| options
);
962 gzos
= new java
.util
.zip
.GZIPOutputStream(b64os
);
964 gzos
.write(source
, off
, len
);
967 catch (java
.io
.IOException e
) {
968 // Catch it and then throw it immediately so that
969 // the finally{} block is called for cleanup.
975 } catch (Exception e
) {
979 } catch (Exception e
) {
983 } catch (Exception e
) {
987 return baos
.toByteArray();
988 } // end if: compress
990 // Else, don't compress. Better not to use streams at all then.
992 boolean breakLines
= (options
& DO_BREAK_LINES
) > 0;
994 //int len43 = len * 4 / 3;
995 //byte[] outBuff = new byte[ ( len43 ) // Main 4:3
996 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
997 // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
998 // Try to determine more precisely how big the array needs to be.
999 // If we get it right, we don't have to do an array copy, and
1000 // we save a bunch of memory.
1001 int encLen
= (len
/ 3) * 4 + (len
% 3 > 0 ?
4 : 0); // Bytes needed for actual encoding
1003 encLen
+= encLen
/ MAX_LINE_LENGTH
; // Plus extra newline characters
1005 byte[] outBuff
= new byte[encLen
];
1012 for (; d
< len2
; d
+= 3, e
+= 4) {
1013 encode3to4(source
, d
+ off
, 3, outBuff
, e
, options
);
1016 if (breakLines
&& lineLength
>= MAX_LINE_LENGTH
) {
1017 outBuff
[e
+ 4] = NEW_LINE
;
1020 } // end if: end of line
1021 } // en dfor: each piece of array
1024 encode3to4(source
, d
+ off
, len
- d
, outBuff
, e
, options
);
1026 } // end if: some padding needed
1029 // Only resize array if we didn't guess it right.
1030 if (e
< outBuff
.length
- 1) {
1031 byte[] finalOut
= new byte[e
];
1032 System
.arraycopy(outBuff
, 0, finalOut
, 0, e
);
1033 //System.err.println("Having to resize array from " + outBuff.length + " to " + e );
1036 //System.err.println("No need to resize array.");
1040 } // end else: don't compress
1042 } // end encodeBytesToBytes
1048 /* ******** D E C O D I N G M E T H O D S ******** */
1052 * Decodes four bytes from array <var>source</var>
1053 * and writes the resulting bytes (up to three of them)
1054 * to <var>destination</var>.
1055 * The source and destination arrays can be manipulated
1056 * anywhere along their length by specifying
1057 * <var>srcOffset</var> and <var>destOffset</var>.
1058 * This method does not check to make sure your arrays
1059 * are large enough to accomodate <var>srcOffset</var> + 4 for
1060 * the <var>source</var> array or <var>destOffset</var> + 3 for
1061 * the <var>destination</var> array.
1062 * This method returns the actual number of bytes that
1063 * were converted from the Base64 encoding.
1064 * <p>This is the lowest level of the decoding methods with
1065 * all possible parameters.</p>
1067 * @param source the array to convert
1068 * @param srcOffset the index where conversion begins
1069 * @param destination the array to hold the conversion
1070 * @param destOffset the index where output will be put
1071 * @param options alphabet type is pulled from this (standard, url-safe, ordered)
1072 * @return the number of decoded bytes converted
1073 * @throws NullPointerException if source or destination arrays are null
1074 * @throws IllegalArgumentException if srcOffset or destOffset are invalid
1075 * or there is not enough room in the array.
1078 private static int decode4to3(
1079 byte[] source
, int srcOffset
,
1080 byte[] destination
, int destOffset
, int options
) {
1082 // Lots of error checking and exception throwing
1083 if (source
== null) {
1084 throw new NullPointerException("Source array was null.");
1086 if (destination
== null) {
1087 throw new NullPointerException("Destination array was null.");
1089 if (srcOffset
< 0 || srcOffset
+ 3 >= source
.length
) {
1090 throw new IllegalArgumentException(String
.format(
1091 "Source array with length %d cannot have offset of %d and still process four bytes.", source
.length
, srcOffset
));
1093 if (destOffset
< 0 || destOffset
+ 2 >= destination
.length
) {
1094 throw new IllegalArgumentException(String
.format(
1095 "Destination array with length %d cannot have offset of %d and still store three bytes.", destination
.length
, destOffset
));
1099 byte[] DECODABET
= getDecodabet(options
);
1102 if (source
[srcOffset
+ 2] == EQUALS_SIGN
) {
1103 // Two ways to do the same thing. Don't know which way I like best.
1104 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
1105 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
1106 int outBuff
= ((DECODABET
[source
[srcOffset
]] & 0xFF) << 18)
1107 | ((DECODABET
[source
[srcOffset
+ 1]] & 0xFF) << 12);
1109 destination
[destOffset
] = (byte) (outBuff
>>> 16);
1114 else if (source
[srcOffset
+ 3] == EQUALS_SIGN
) {
1115 // Two ways to do the same thing. Don't know which way I like best.
1116 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
1117 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
1118 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
1119 int outBuff
= ((DECODABET
[source
[srcOffset
]] & 0xFF) << 18)
1120 | ((DECODABET
[source
[srcOffset
+ 1]] & 0xFF) << 12)
1121 | ((DECODABET
[source
[srcOffset
+ 2]] & 0xFF) << 6);
1123 destination
[destOffset
] = (byte) (outBuff
>>> 16);
1124 destination
[destOffset
+ 1] = (byte) (outBuff
>>> 8);
1130 // Two ways to do the same thing. Don't know which way I like best.
1131 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
1132 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
1133 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
1134 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
1135 int outBuff
= ((DECODABET
[source
[srcOffset
]] & 0xFF) << 18)
1136 | ((DECODABET
[source
[srcOffset
+ 1]] & 0xFF) << 12)
1137 | ((DECODABET
[source
[srcOffset
+ 2]] & 0xFF) << 6)
1138 | ((DECODABET
[source
[srcOffset
+ 3]] & 0xFF));
1141 destination
[destOffset
] = (byte) (outBuff
>> 16);
1142 destination
[destOffset
+ 1] = (byte) (outBuff
>> 8);
1143 destination
[destOffset
+ 2] = (byte) (outBuff
);
1147 } // end decodeToBytes
1151 * Low-level access to decoding ASCII characters in
1152 * the form of a byte array. <strong>Ignores GUNZIP option, if
1153 * it's set.</strong> This is not generally a recommended method,
1154 * although it is used internally as part of the decoding process.
1155 * Special case: if len = 0, an empty array is returned. Still,
1156 * if you need more speed and reduced memory footprint (and aren't
1157 * gzipping), consider this method.
1159 * @param source The Base64 encoded data
1160 * @return decoded data
1163 public static byte[] decode(byte[] source
) {
1164 byte[] decoded
= null;
1166 decoded
= decode(source
, 0, source
.length
, Base64
.NO_OPTIONS
);
1167 } catch (java
.io
.IOException ex
) {
1168 assert false : "IOExceptions only come from GZipping, which is turned off: " + ex
.getMessage();
1175 * Low-level access to decoding ASCII characters in
1176 * the form of a byte array. <strong>Ignores GUNZIP option, if
1177 * it's set.</strong> This is not generally a recommended method,
1178 * although it is used internally as part of the decoding process.
1179 * Special case: if len = 0, an empty array is returned. Still,
1180 * if you need more speed and reduced memory footprint (and aren't
1181 * gzipping), consider this method.
1183 * @param source The Base64 encoded data
1184 * @param off The offset of where to begin decoding
1185 * @param len The length of characters to decode
1186 * @param options Can specify options such as alphabet type to use
1187 * @return decoded data
1188 * @throws java.io.IOException If bogus characters exist in source data
1191 public static byte[] decode(byte[] source
, int off
, int len
, int options
)
1192 throws java
.io
.IOException
{
1194 // Lots of error checking and exception throwing
1195 if (source
== null) {
1196 throw new NullPointerException("Cannot decode null source array.");
1198 if (off
< 0 || off
+ len
> source
.length
) {
1199 throw new IllegalArgumentException(String
.format(
1200 "Source array with length %d cannot have offset of %d and process %d bytes.", source
.length
, off
, len
));
1205 } else if (len
< 4) {
1206 throw new IllegalArgumentException(
1207 "Base64-encoded string must have at least four characters, but length specified was " + len
);
1210 byte[] DECODABET
= getDecodabet(options
);
1212 int len34
= len
* 3 / 4; // Estimate on array size
1213 byte[] outBuff
= new byte[len34
]; // Upper limit on size of output
1214 int outBuffPosn
= 0; // Keep track of where we're writing
1216 byte[] b4
= new byte[4]; // Four byte buffer from source, eliminating white space
1217 int b4Posn
= 0; // Keep track of four byte input buffer
1218 int i
= 0; // Source array counter
1219 byte sbiCrop
= 0; // Low seven bits (ASCII) of input
1220 byte sbiDecode
= 0; // Special value from DECODABET
1222 for (i
= off
; i
< off
+ len
; i
++) { // Loop through source
1224 sbiCrop
= (byte) (source
[i
] & 0x7f); // Only the low seven bits
1225 sbiDecode
= DECODABET
[sbiCrop
]; // Special value
1227 // White space, Equals sign, or legit Base64 character
1228 // Note the values such as -5 and -9 in the
1229 // DECODABETs at the top of the file.
1230 if (sbiDecode
>= WHITE_SPACE_ENC
) {
1231 if (sbiDecode
>= EQUALS_SIGN_ENC
) {
1232 b4
[b4Posn
++] = sbiCrop
; // Save non-whitespace
1233 if (b4Posn
> 3) { // Time to decode?
1234 outBuffPosn
+= decode4to3(b4
, 0, outBuff
, outBuffPosn
, options
);
1237 // If that was the equals sign, break out of 'for' loop
1238 if (sbiCrop
== EQUALS_SIGN
) {
1240 } // end if: equals sign
1241 } // end if: quartet built
1242 } // end if: equals sign or better
1243 } // end if: white space, equals sign or better
1245 // There's a bad input character in the Base64 stream.
1246 throw new java
.io
.IOException(String
.format(
1247 "Bad Base64 input character '%c' in array position %d", source
[i
], i
));
1249 } // each input character
1251 byte[] out
= new byte[outBuffPosn
];
1252 System
.arraycopy(outBuff
, 0, out
, 0, outBuffPosn
);
1258 * Decodes data from Base64 notation, automatically
1259 * detecting gzip-compressed data and decompressing it.
1261 * @param s the string to decode
1262 * @return the decoded data
1263 * @throws java.io.IOException If there is a problem
1266 public static byte[] decode(String s
) throws java
.io
.IOException
{
1267 return decode(s
, NO_OPTIONS
);
1271 public static byte[] decodeWithoutPadding(String source
) throws java
.io
.IOException
{
1272 int padding
= source
.length() % 4;
1274 if (padding
== 1) source
= source
+ "=";
1275 else if (padding
== 2) source
= source
+ "==";
1276 else if (padding
== 3) source
= source
+ "=";
1278 return decode(source
);
1283 * Decodes data from Base64 notation, automatically
1284 * detecting gzip-compressed data and decompressing it.
1286 * @param s the string to decode
1287 * @param options encode options such as URL_SAFE
1288 * @return the decoded data
1289 * @throws java.io.IOException if there is an error
1290 * @throws NullPointerException if <tt>s</tt> is null
1293 public static byte[] decode(String s
, int options
) throws java
.io
.IOException
{
1296 throw new NullPointerException("Input string was null.");
1301 bytes
= s
.getBytes(PREFERRED_ENCODING
);
1303 catch (java
.io
.UnsupportedEncodingException uee
) {
1304 bytes
= s
.getBytes();
1309 bytes
= decode(bytes
, 0, bytes
.length
, options
);
1311 // Check to see if it's gzip-compressed
1312 // GZIP Magic Two-Byte Number: 0x8b1f (35615)
1313 boolean dontGunzip
= (options
& DONT_GUNZIP
) != 0;
1314 if ((bytes
!= null) && (bytes
.length
>= 4) && (!dontGunzip
)) {
1316 int head
= ((int) bytes
[0] & 0xff) | ((bytes
[1] << 8) & 0xff00);
1317 if (java
.util
.zip
.GZIPInputStream
.GZIP_MAGIC
== head
) {
1318 java
.io
.ByteArrayInputStream bais
= null;
1319 java
.util
.zip
.GZIPInputStream gzis
= null;
1320 java
.io
.ByteArrayOutputStream baos
= null;
1321 byte[] buffer
= new byte[2048];
1325 baos
= new java
.io
.ByteArrayOutputStream();
1326 bais
= new java
.io
.ByteArrayInputStream(bytes
);
1327 gzis
= new java
.util
.zip
.GZIPInputStream(bais
);
1329 while ((length
= gzis
.read(buffer
)) >= 0) {
1330 baos
.write(buffer
, 0, length
);
1331 } // end while: reading input
1333 // No error? Get new bytes.
1334 bytes
= baos
.toByteArray();
1337 catch (java
.io
.IOException e
) {
1338 e
.printStackTrace();
1339 // Just return originally-decoded bytes
1344 } catch (Exception e
) {
1348 } catch (Exception e
) {
1352 } catch (Exception e
) {
1356 } // end if: gzipped
1357 } // end if: bytes.length >= 2
1364 * Attempts to decode Base64 data and deserialize a Java
1365 * Object within. Returns <tt>null</tt> if there was an error.
1367 * @param encodedObject The Base64 data to decode
1368 * @return The decoded and deserialized object
1369 * @throws NullPointerException if encodedObject is null
1370 * @throws java.io.IOException if there is a general error
1371 * @throws ClassNotFoundException if the decoded object is of a
1372 * class that cannot be found by the JVM
1375 public static Object
decodeToObject(String encodedObject
)
1376 throws java
.io
.IOException
, java
.lang
.ClassNotFoundException
{
1377 return decodeToObject(encodedObject
, NO_OPTIONS
, null);
1382 * Attempts to decode Base64 data and deserialize a Java
1383 * Object within. Returns <tt>null</tt> if there was an error.
1384 * If <tt>loader</tt> is not null, it will be the class loader
1385 * used when deserializing.
1387 * @param encodedObject The Base64 data to decode
1388 * @param options Various parameters related to decoding
1389 * @param loader Optional class loader to use in deserializing classes.
1390 * @return The decoded and deserialized object
1391 * @throws NullPointerException if encodedObject is null
1392 * @throws java.io.IOException if there is a general error
1393 * @throws ClassNotFoundException if the decoded object is of a
1394 * class that cannot be found by the JVM
1397 public static Object
decodeToObject(
1398 String encodedObject
, int options
, final ClassLoader loader
)
1399 throws java
.io
.IOException
, java
.lang
.ClassNotFoundException
{
1401 // Decode and gunzip if necessary
1402 byte[] objBytes
= decode(encodedObject
, options
);
1404 java
.io
.ByteArrayInputStream bais
= null;
1405 java
.io
.ObjectInputStream ois
= null;
1409 bais
= new java
.io
.ByteArrayInputStream(objBytes
);
1411 // If no custom class loader is provided, use Java's builtin OIS.
1412 if (loader
== null) {
1413 ois
= new java
.io
.ObjectInputStream(bais
);
1414 } // end if: no loader provided
1416 // Else make a customized object input stream that uses
1417 // the provided class loader.
1419 ois
= new java
.io
.ObjectInputStream(bais
) {
1421 public Class
<?
> resolveClass(java
.io
.ObjectStreamClass streamClass
)
1422 throws java
.io
.IOException
, ClassNotFoundException
{
1423 Class c
= Class
.forName(streamClass
.getName(), false, loader
);
1425 return super.resolveClass(streamClass
);
1427 return c
; // Class loader knows of this class.
1428 } // end else: not null
1429 } // end resolveClass
1431 } // end else: no custom class loader
1433 obj
= ois
.readObject();
1435 catch (java
.io
.IOException e
) {
1436 throw e
; // Catch and throw in order to execute finally{}
1438 catch (java
.lang
.ClassNotFoundException e
) {
1439 throw e
; // Catch and throw in order to execute finally{}
1444 } catch (Exception e
) {
1448 } catch (Exception e
) {
1453 } // end decodeObject
1457 * Convenience method for encoding data to a file.
1459 * <p>As of v 2.3, if there is a error,
1460 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1461 * In earlier versions, it just returned false, but
1462 * in retrospect that's a pretty poor way to handle it.</p>
1464 * @param dataToEncode byte array of data to encode in base64 form
1465 * @param filename Filename for saving encoded data
1466 * @throws java.io.IOException if there is an error
1467 * @throws NullPointerException if dataToEncode is null
1470 public static void encodeToFile(byte[] dataToEncode
, String filename
)
1471 throws java
.io
.IOException
{
1473 if (dataToEncode
== null) {
1474 throw new NullPointerException("Data to encode was null.");
1477 Base64
.OutputStream bos
= null;
1479 bos
= new Base64
.OutputStream(
1480 new java
.io
.FileOutputStream(filename
), Base64
.ENCODE
);
1481 bos
.write(dataToEncode
);
1483 catch (java
.io
.IOException e
) {
1484 throw e
; // Catch and throw to execute finally{} block
1485 } // end catch: java.io.IOException
1489 } catch (Exception e
) {
1493 } // end encodeToFile
1497 * Convenience method for decoding data to a file.
1499 * <p>As of v 2.3, if there is a error,
1500 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1501 * In earlier versions, it just returned false, but
1502 * in retrospect that's a pretty poor way to handle it.</p>
1504 * @param dataToDecode Base64-encoded data as a string
1505 * @param filename Filename for saving decoded data
1506 * @throws java.io.IOException if there is an error
1509 public static void decodeToFile(String dataToDecode
, String filename
)
1510 throws java
.io
.IOException
{
1512 Base64
.OutputStream bos
= null;
1514 bos
= new Base64
.OutputStream(
1515 new java
.io
.FileOutputStream(filename
), Base64
.DECODE
);
1516 bos
.write(dataToDecode
.getBytes(PREFERRED_ENCODING
));
1518 catch (java
.io
.IOException e
) {
1519 throw e
; // Catch and throw to execute finally{} block
1520 } // end catch: java.io.IOException
1524 } catch (Exception e
) {
1528 } // end decodeToFile
1532 * Convenience method for reading a base64-encoded
1533 * file and decoding it.
1535 * <p>As of v 2.3, if there is a error,
1536 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1537 * In earlier versions, it just returned false, but
1538 * in retrospect that's a pretty poor way to handle it.</p>
1540 * @param filename Filename for reading encoded data
1541 * @return decoded byte array
1542 * @throws java.io.IOException if there is an error
1545 public static byte[] decodeFromFile(String filename
)
1546 throws java
.io
.IOException
{
1548 byte[] decodedData
= null;
1549 Base64
.InputStream bis
= null;
1551 // Set up some useful variables
1552 java
.io
.File file
= new java
.io
.File(filename
);
1553 byte[] buffer
= null;
1557 // Check for size of file
1558 if (file
.length() > Integer
.MAX_VALUE
) {
1559 throw new java
.io
.IOException("File is too big for this convenience method (" + file
.length() + " bytes).");
1560 } // end if: file too big for int index
1561 buffer
= new byte[(int) file
.length()];
1564 bis
= new Base64
.InputStream(
1565 new java
.io
.BufferedInputStream(
1566 new java
.io
.FileInputStream(file
)), Base64
.DECODE
);
1569 while ((numBytes
= bis
.read(buffer
, length
, 4096)) >= 0) {
1573 // Save in a variable to return
1574 decodedData
= new byte[length
];
1575 System
.arraycopy(buffer
, 0, decodedData
, 0, length
);
1578 catch (java
.io
.IOException e
) {
1579 throw e
; // Catch and release to execute finally{}
1580 } // end catch: java.io.IOException
1584 } catch (Exception e
) {
1589 } // end decodeFromFile
1593 * Convenience method for reading a binary file
1594 * and base64-encoding it.
1596 * <p>As of v 2.3, if there is a error,
1597 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
1598 * In earlier versions, it just returned false, but
1599 * in retrospect that's a pretty poor way to handle it.</p>
1601 * @param filename Filename for reading binary data
1602 * @return base64-encoded string
1603 * @throws java.io.IOException if there is an error
1606 public static String
encodeFromFile(String filename
)
1607 throws java
.io
.IOException
{
1609 String encodedData
= null;
1610 Base64
.InputStream bis
= null;
1612 // Set up some useful variables
1613 java
.io
.File file
= new java
.io
.File(filename
);
1614 byte[] buffer
= new byte[Math
.max((int) (file
.length() * 1.4), 40)]; // Need max() for math on small files (v2.2.1)
1619 bis
= new Base64
.InputStream(
1620 new java
.io
.BufferedInputStream(
1621 new java
.io
.FileInputStream(file
)), Base64
.ENCODE
);
1624 while ((numBytes
= bis
.read(buffer
, length
, 4096)) >= 0) {
1628 // Save in a variable to return
1629 encodedData
= new String(buffer
, 0, length
, Base64
.PREFERRED_ENCODING
);
1632 catch (java
.io
.IOException e
) {
1633 throw e
; // Catch and release to execute finally{}
1634 } // end catch: java.io.IOException
1638 } catch (Exception e
) {
1643 } // end encodeFromFile
1646 * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
1648 * @param infile Input file
1649 * @param outfile Output file
1650 * @throws java.io.IOException if there is an error
1653 public static void encodeFileToFile(String infile
, String outfile
)
1654 throws java
.io
.IOException
{
1656 String encoded
= Base64
.encodeFromFile(infile
);
1657 java
.io
.OutputStream out
= null;
1659 out
= new java
.io
.BufferedOutputStream(
1660 new java
.io
.FileOutputStream(outfile
));
1661 out
.write(encoded
.getBytes("US-ASCII")); // Strict, 7-bit output.
1663 catch (java
.io
.IOException e
) {
1664 throw e
; // Catch and release to execute finally{}
1669 } catch (Exception ex
) {
1672 } // end encodeFileToFile
1676 * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
1678 * @param infile Input file
1679 * @param outfile Output file
1680 * @throws java.io.IOException if there is an error
1683 public static void decodeFileToFile(String infile
, String outfile
)
1684 throws java
.io
.IOException
{
1686 byte[] decoded
= Base64
.decodeFromFile(infile
);
1687 java
.io
.OutputStream out
= null;
1689 out
= new java
.io
.BufferedOutputStream(
1690 new java
.io
.FileOutputStream(outfile
));
1693 catch (java
.io
.IOException e
) {
1694 throw e
; // Catch and release to execute finally{}
1699 } catch (Exception ex
) {
1702 } // end decodeFileToFile
1705 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
1709 * A {@link Base64.InputStream} will read data from another
1710 * <tt>java.io.InputStream</tt>, given in the constructor,
1711 * and encode/decode to/from Base64 notation on the fly.
1716 public static class InputStream
extends java
.io
.FilterInputStream
{
1718 private boolean encode
; // Encoding or decoding
1719 private int position
; // Current position in the buffer
1720 private byte[] buffer
; // Small buffer holding converted data
1721 private int bufferLength
; // Length of buffer (3 or 4)
1722 private int numSigBytes
; // Number of meaningful bytes in the buffer
1723 private int lineLength
;
1724 private boolean breakLines
; // Break lines at less than 80 characters
1725 private int options
; // Record options used to create the stream.
1726 private byte[] decodabet
; // Local copies to avoid extra method calls
1730 * Constructs a {@link Base64.InputStream} in DECODE mode.
1732 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1735 public InputStream(java
.io
.InputStream
in) {
1737 } // end constructor
1741 * Constructs a {@link Base64.InputStream} in
1742 * either ENCODE or DECODE mode.
1744 * Valid options:<pre>
1745 * ENCODE or DECODE: Encode or Decode as data is read.
1746 * DO_BREAK_LINES: break lines at 76 characters
1747 * (only meaningful when encoding)</i>
1750 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
1752 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1753 * @param options Specified options
1754 * @see Base64#ENCODE
1755 * @see Base64#DECODE
1756 * @see Base64#DO_BREAK_LINES
1759 public InputStream(java
.io
.InputStream
in, int options
) {
1762 this.options
= options
; // Record for later
1763 this.breakLines
= (options
& DO_BREAK_LINES
) > 0;
1764 this.encode
= (options
& ENCODE
) > 0;
1765 this.bufferLength
= encode ?
4 : 3;
1766 this.buffer
= new byte[bufferLength
];
1768 this.lineLength
= 0;
1769 this.decodabet
= getDecodabet(options
);
1770 } // end constructor
1773 * Reads enough of the input stream to convert
1774 * to/from Base64 and returns the next byte.
1780 public int read() throws java
.io
.IOException
{
1782 // Do we need to get data?
1785 byte[] b3
= new byte[3];
1786 int numBinaryBytes
= 0;
1787 for (int i
= 0; i
< 3; i
++) {
1790 // If end of stream, b is -1.
1795 break; // out of for loop
1796 } // end else: end of stream
1798 } // end for: each needed input byte
1800 if (numBinaryBytes
> 0) {
1801 encode3to4(b3
, 0, numBinaryBytes
, buffer
, 0, options
);
1804 } // end if: got data
1806 return -1; // Must be end of stream
1808 } // end if: encoding
1812 byte[] b4
= new byte[4];
1814 for (i
= 0; i
< 4; i
++) {
1815 // Read four "meaningful" bytes:
1820 while (b
>= 0 && decodabet
[b
& 0x7f] <= WHITE_SPACE_ENC
);
1823 break; // Reads a -1 if end of stream
1824 } // end if: end of stream
1827 } // end for: each needed input byte
1830 numSigBytes
= decode4to3(b4
, 0, buffer
, 0, options
);
1832 } // end if: got four characters
1835 } // end else if: also padded correctly
1837 // Must have broken out from above.
1838 throw new java
.io
.IOException("Improperly padded Base64 input.");
1841 } // end else: decode
1842 } // end else: get data
1845 if (position
>= 0) {
1846 // End of relevant data?
1847 if ( /*!encode &&*/ position
>= numSigBytes
) {
1849 } // end if: got data
1851 if (encode
&& breakLines
&& lineLength
>= MAX_LINE_LENGTH
) {
1856 lineLength
++; // This isn't important when decoding
1857 // but throwing an extra "if" seems
1858 // just as wasteful.
1860 int b
= buffer
[position
++];
1862 if (position
>= bufferLength
) {
1866 return b
& 0xFF; // This is how you "cast" a byte that's
1867 // intended to be unsigned.
1869 } // end if: position >= 0
1873 throw new java
.io
.IOException("Error in Base64 code reading stream.");
1879 * Calls {@link #read()} repeatedly until the end of stream
1880 * is reached or <var>len</var> bytes are read.
1881 * Returns number of bytes read into array or -1 if
1882 * end of stream is encountered.
1884 * @param dest array to hold values
1885 * @param off offset for array
1886 * @param len max number of bytes to read into array
1887 * @return bytes read into array or -1 if end of stream is encountered.
1891 public int read(byte[] dest
, int off
, int len
)
1892 throws java
.io
.IOException
{
1895 for (i
= 0; i
< len
; i
++) {
1899 dest
[off
+ i
] = (byte) b
;
1900 } else if (i
== 0) {
1903 break; // Out of 'for' loop
1904 } // Out of 'for' loop
1905 } // end for: each byte read
1909 } // end inner class InputStream
1916 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
1920 * A {@link Base64.OutputStream} will write data to another
1921 * <tt>java.io.OutputStream</tt>, given in the constructor,
1922 * and encode/decode to/from Base64 notation on the fly.
1927 public static class OutputStream
extends java
.io
.FilterOutputStream
{
1929 private boolean encode
;
1930 private int position
;
1931 private byte[] buffer
;
1932 private int bufferLength
;
1933 private int lineLength
;
1934 private boolean breakLines
;
1935 private byte[] b4
; // Scratch used in a few places
1936 private boolean suspendEncoding
;
1937 private int options
; // Record for later
1938 private byte[] decodabet
; // Local copies to avoid extra method calls
1941 * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1943 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1946 public OutputStream(java
.io
.OutputStream out
) {
1948 } // end constructor
1952 * Constructs a {@link Base64.OutputStream} in
1953 * either ENCODE or DECODE mode.
1955 * Valid options:<pre>
1956 * ENCODE or DECODE: Encode or Decode as data is read.
1957 * DO_BREAK_LINES: don't break lines at 76 characters
1958 * (only meaningful when encoding)</i>
1961 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
1963 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1964 * @param options Specified options.
1965 * @see Base64#ENCODE
1966 * @see Base64#DECODE
1967 * @see Base64#DO_BREAK_LINES
1970 public OutputStream(java
.io
.OutputStream out
, int options
) {
1972 this.breakLines
= (options
& DO_BREAK_LINES
) != 0;
1973 this.encode
= (options
& ENCODE
) != 0;
1974 this.bufferLength
= encode ?
3 : 4;
1975 this.buffer
= new byte[bufferLength
];
1977 this.lineLength
= 0;
1978 this.suspendEncoding
= false;
1979 this.b4
= new byte[4];
1980 this.options
= options
;
1981 this.decodabet
= getDecodabet(options
);
1982 } // end constructor
1986 * Writes the byte to the output stream after
1987 * converting to/from Base64 notation.
1988 * When encoding, bytes are buffered three
1989 * at a time before the output stream actually
1990 * gets a write() call.
1991 * When decoding, bytes are buffered four
1994 * @param theByte the byte to write
1998 public void write(int theByte
)
1999 throws java
.io
.IOException
{
2000 // Encoding suspended?
2001 if (suspendEncoding
) {
2002 this.out
.write(theByte
);
2004 } // end if: supsended
2008 buffer
[position
++] = (byte) theByte
;
2009 if (position
>= bufferLength
) { // Enough to encode.
2011 this.out
.write(encode3to4(b4
, buffer
, bufferLength
, options
));
2014 if (breakLines
&& lineLength
>= MAX_LINE_LENGTH
) {
2015 this.out
.write(NEW_LINE
);
2017 } // end if: end of line
2020 } // end if: enough to output
2021 } // end if: encoding
2025 // Meaningful Base64 character?
2026 if (decodabet
[theByte
& 0x7f] > WHITE_SPACE_ENC
) {
2027 buffer
[position
++] = (byte) theByte
;
2028 if (position
>= bufferLength
) { // Enough to output.
2030 int len
= Base64
.decode4to3(buffer
, 0, b4
, 0, options
);
2031 out
.write(b4
, 0, len
);
2033 } // end if: enough to output
2034 } // end if: meaningful base64 character
2035 else if (decodabet
[theByte
& 0x7f] != WHITE_SPACE_ENC
) {
2036 throw new java
.io
.IOException("Invalid character in Base64 data.");
2037 } // end else: not white space either
2038 } // end else: decoding
2043 * Calls {@link #write(int)} repeatedly until <var>len</var>
2044 * bytes are written.
2046 * @param theBytes array from which to read bytes
2047 * @param off offset for array
2048 * @param len max number of bytes to read into array
2052 public void write(byte[] theBytes
, int off
, int len
)
2053 throws java
.io
.IOException
{
2054 // Encoding suspended?
2055 if (suspendEncoding
) {
2056 this.out
.write(theBytes
, off
, len
);
2058 } // end if: supsended
2060 for (int i
= 0; i
< len
; i
++) {
2061 write(theBytes
[off
+ i
]);
2062 } // end for: each byte written
2068 * Method added by PHIL. [Thanks, PHIL. -Rob]
2069 * This pads the buffer without closing the stream.
2071 * @throws java.io.IOException if there's an error.
2073 public void flushBase64() throws java
.io
.IOException
{
2076 out
.write(encode3to4(b4
, buffer
, position
, options
));
2078 } // end if: encoding
2080 throw new java
.io
.IOException("Base64 input not properly padded.");
2081 } // end else: decoding
2082 } // end if: buffer partially full
2088 * Flushes and closes (I think, in the superclass) the stream.
2093 public void close() throws java
.io
.IOException
{
2094 // 1. Ensure that pending characters are written
2097 // 2. Actually close the stream
2098 // Base class both flushes and closes.
2107 * Suspends encoding of the stream.
2108 * May be helpful if you need to embed a piece of
2109 * base64-encoded data in a stream.
2111 * @throws java.io.IOException if there's an error flushing
2114 public void suspendEncoding() throws java
.io
.IOException
{
2116 this.suspendEncoding
= true;
2117 } // end suspendEncoding
2121 * Resumes encoding of the stream.
2122 * May be helpful if you need to embed a piece of
2123 * base64-encoded data in a stream.
2127 public void resumeEncoding() {
2128 this.suspendEncoding
= false;
2129 } // end resumeEncoding
2132 } // end inner class OutputStream
2135 } // end class Base64