1 package net.mattmccutchen.measurements;
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>
11 * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
12 * when using very small files (~< 40 bytes).</li>
13 * <li>v2.2 - Added some helper methods for encoding/decoding directly from
14 * one file to the next. Also added a main() method to support command line
15 * encoding/decoding from one file to the next. Also added these Base64 dialects:
17 * <li>The default is RFC3548 format.</li>
18 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
19 * URL and file name friendly format as described in Section 4 of RFC3548.
20 * http://www.faqs.org/rfcs/rfc3548.html</li>
21 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
22 * URL and file name friendly format that preserves lexical ordering as described
23 * in http://www.faqs.org/qa/rfcc-1940.html</li>
25 * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
26 * for contributing the new Base64 dialects.
29 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
30 * some convenience methods for reading and writing to and from files.</li>
31 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
32 * with other encodings (like EBCDIC).</li>
33 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
34 * encoded data was a single byte.</li>
35 * <li>v2.0 - I got rid of methods that used booleans to set options.
36 * Now everything is more consolidated and cleaner. The code now detects
37 * when data that's being decoded is gzip-compressed and will decompress it
38 * automatically. Generally things are cleaner. You'll probably have to
39 * change some method calls that you were making to support the new
40 * options format (<tt>int</tt>s that you "OR" together).</li>
41 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
42 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
43 * Added the ability to "suspend" encoding in the Output Stream so
44 * you can turn on and off the encoding if you need to embed base64
45 * data in an otherwise "normal" stream (like an XML file).</li>
46 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
47 * This helps when using GZIP streams.
48 * Added the ability to GZip-compress objects before encoding them.</li>
49 * <li>v1.4 - Added helper methods to read/write files.</li>
50 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
51 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
52 * where last buffer being read, if not completely full, was not returned.</li>
53 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
54 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
58 * I am placing this code in the Public Domain. Do with it as you will.
59 * This software comes with no guarantees or warranties but with
60 * plenty of well-wishing instead!
61 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
62 * periodically to check for updates or to contribute improvements.
65 * @author Robert Harder
66 * @author rob@iharder.net
72 /* ******** P U B L I C F I E L D S ******** */
75 /** No options specified. Value is zero. */
76 public final static int NO_OPTIONS = 0;
78 /** Specify encoding. */
79 public final static int ENCODE = 1;
82 /** Specify decoding. */
83 public final static int DECODE = 0;
86 /** Specify that data should be gzip-compressed. */
87 public final static int GZIP = 2;
90 /** Don't break lines when encoding (violates strict Base64 specification) */
91 public final static int DONT_BREAK_LINES = 8;
94 * Encode using Base64-like encoding that is URL- and Filename-safe as described
95 * in Section 4 of RFC3548:
96 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
97 * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
98 * or at the very least should not be called Base64 without also specifying that is
99 * was encoded using the URL- and Filename-safe dialect.
101 public final static int URL_SAFE = 16;
105 * Encode using the special "ordered" dialect of Base64 described here:
106 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
108 public final static int ORDERED = 32;
112 * In {@link #decode(String, int)}, do not automatically ungzip data that
113 * has the gzip magic number.
115 * Modification by Matt!
117 public final static int NO_GZIP_MAGIC = 64;
119 /* ******** P R I V A T E F I E L D S ******** */
122 /** Maximum line length (76) of Base64 output. */
123 private final static int MAX_LINE_LENGTH = 76;
126 /** The equals sign (=) as a byte. */
127 private final static byte EQUALS_SIGN = (byte)'=';
130 /** The new line character (\n) as a byte. */
131 private final static byte NEW_LINE = (byte)'\n';
134 /** Preferred encoding. */
135 private final static String PREFERRED_ENCODING = "UTF-8";
138 // I think I end up not using the BAD_ENCODING indicator.
139 //private final static byte BAD_ENCODING = -9; // Indicates error in encoding
140 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
141 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
144 /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
146 /** The 64 valid Base64 values. */
147 //private final static byte[] ALPHABET;
148 /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
149 private final static byte[] _STANDARD_ALPHABET =
151 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
152 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
153 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
154 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
155 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
156 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
157 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
158 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
159 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
160 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
165 * Translates a Base64 value to either its 6-bit reconstruction value
166 * or a negative number indicating some other meaning.
168 private final static byte[] _STANDARD_DECODABET =
170 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
171 -5,-5, // Whitespace: Tab and Linefeed
172 -9,-9, // Decimal 11 - 12
173 -5, // Whitespace: Carriage Return
174 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
175 -9,-9,-9,-9,-9, // Decimal 27 - 31
176 -5, // Whitespace: Space
177 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
178 62, // Plus sign at decimal 43
179 -9,-9,-9, // Decimal 44 - 46
180 63, // Slash at decimal 47
181 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
182 -9,-9,-9, // Decimal 58 - 60
183 -1, // Equals sign at decimal 61
184 -9,-9,-9, // Decimal 62 - 64
185 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
186 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
187 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
188 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
189 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
190 -9,-9,-9,-9 // Decimal 123 - 126
191 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
192 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
193 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
194 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
195 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
196 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
197 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
198 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
199 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
200 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
204 /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
207 * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
208 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
209 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
211 private final static byte[] _URL_SAFE_ALPHABET =
213 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
214 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
215 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
216 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
217 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
218 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
219 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
220 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
221 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
222 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
226 * Used in decoding URL- and Filename-safe dialects of Base64.
228 private final static byte[] _URL_SAFE_DECODABET =
230 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
231 -5,-5, // Whitespace: Tab and Linefeed
232 -9,-9, // Decimal 11 - 12
233 -5, // Whitespace: Carriage Return
234 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
235 -9,-9,-9,-9,-9, // Decimal 27 - 31
236 -5, // Whitespace: Space
237 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
238 -9, // Plus sign at decimal 43
240 62, // Minus sign at decimal 45
242 -9, // Slash at decimal 47
243 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
244 -9,-9,-9, // Decimal 58 - 60
245 -1, // Equals sign at decimal 61
246 -9,-9,-9, // Decimal 62 - 64
247 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
248 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
249 -9,-9,-9,-9, // Decimal 91 - 94
250 63, // Underscore at decimal 95
252 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
253 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
254 -9,-9,-9,-9 // Decimal 123 - 126
255 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
256 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
257 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
258 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
259 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
260 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
261 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
262 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
263 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
264 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
269 /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
272 * I don't get the point of this technique, but it is described here:
273 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
275 private final static byte[] _ORDERED_ALPHABET =
278 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
279 (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
280 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
281 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
282 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
283 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
285 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
286 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
287 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
288 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
292 * Used in decoding the "ordered" dialect of Base64.
294 private final static byte[] _ORDERED_DECODABET =
296 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
297 -5,-5, // Whitespace: Tab and Linefeed
298 -9,-9, // Decimal 11 - 12
299 -5, // Whitespace: Carriage Return
300 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
301 -9,-9,-9,-9,-9, // Decimal 27 - 31
302 -5, // Whitespace: Space
303 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
304 -9, // Plus sign at decimal 43
306 0, // Minus sign at decimal 45
308 -9, // Slash at decimal 47
309 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
310 -9,-9,-9, // Decimal 58 - 60
311 -1, // Equals sign at decimal 61
312 -9,-9,-9, // Decimal 62 - 64
313 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
314 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
315 -9,-9,-9,-9, // Decimal 91 - 94
316 37, // Underscore at decimal 95
318 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
319 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
320 -9,-9,-9,-9 // Decimal 123 - 126
321 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
322 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
323 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
324 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
325 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
326 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
327 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
328 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
329 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
330 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
334 /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
338 * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
339 * the options specified.
340 * It's possible, though silly, to specify ORDERED and URLSAFE
341 * in which case one of them will be picked, though there is
342 * no guarantee as to which one will be picked.
344 private final static byte[] getAlphabet( int options )
346 if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET;
347 else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET;
348 else return _STANDARD_ALPHABET;
354 * Returns one of the _SOMETHING_DECODABET byte arrays depending on
355 * the options specified.
356 * It's possible, though silly, to specify ORDERED and URL_SAFE
357 * in which case one of them will be picked, though there is
358 * no guarantee as to which one will be picked.
360 private final static byte[] getDecodabet( int options )
362 if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET;
363 else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET;
364 else return _STANDARD_DECODABET;
370 /** Defeats instantiation. */
375 * Encodes or decodes two files from the command line;
376 * <strong>feel free to delete this method (in fact you probably should)
377 * if you're embedding this code into a larger program.</strong>
379 public final static void main( String[] args )
381 if( args.length < 3 ){
382 usage("Not enough arguments.");
383 } // end if: args.length < 3
385 String flag = args[0];
386 String infile = args[1];
387 String outfile = args[2];
388 if( flag.equals( "-e" ) ){
389 Base64.encodeFileToFile( infile, outfile );
391 else if( flag.equals( "-d" ) ) {
392 Base64.decodeFileToFile( infile, outfile );
393 } // end else if: decode
395 usage( "Unknown flag: " + flag );
401 * Prints command line usage.
403 * @param msg A message to include with usage info.
405 private final static void usage( String msg )
407 System.err.println( msg );
408 System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" );
412 /* ******** E N C O D I N G M E T H O D S ******** */
416 * Encodes up to the first three bytes of array <var>threeBytes</var>
417 * and returns a four-byte array in Base64 notation.
418 * The actual number of significant bytes in your array is
419 * given by <var>numSigBytes</var>.
420 * The array <var>threeBytes</var> needs only be as big as
421 * <var>numSigBytes</var>.
422 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
424 * @param b4 A reusable byte array to reduce array instantiation
425 * @param threeBytes the array to convert
426 * @param numSigBytes the number of significant bytes in your array
427 * @return four byte array in Base64 notation.
430 private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options )
432 encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
438 * <p>Encodes up to three bytes of the array <var>source</var>
439 * and writes the resulting four Base64 bytes to <var>destination</var>.
440 * The source and destination arrays can be manipulated
441 * anywhere along their length by specifying
442 * <var>srcOffset</var> and <var>destOffset</var>.
443 * This method does not check to make sure your arrays
444 * are large enough to accomodate <var>srcOffset</var> + 3 for
445 * the <var>source</var> array or <var>destOffset</var> + 4 for
446 * the <var>destination</var> array.
447 * The actual number of significant bytes in your array is
448 * given by <var>numSigBytes</var>.</p>
449 * <p>This is the lowest level of the encoding methods with
450 * all possible parameters.</p>
452 * @param source the array to convert
453 * @param srcOffset the index where conversion begins
454 * @param numSigBytes the number of significant bytes in your array
455 * @param destination the array to hold the conversion
456 * @param destOffset the index where output will be put
457 * @return the <var>destination</var> array
460 private static byte[] encode3to4(
461 byte[] source, int srcOffset, int numSigBytes,
462 byte[] destination, int destOffset, int options )
464 byte[] ALPHABET = getAlphabet( options );
467 // 01234567890123456789012345678901 Bit position
468 // --------000000001111111122222222 Array position from threeBytes
469 // --------| || || || | Six bit groups to index ALPHABET
470 // >>18 >>12 >> 6 >> 0 Right shift necessary
471 // 0x3f 0x3f 0x3f Additional AND
473 // Create buffer with zero-padding if there are only one or two
474 // significant bytes passed in the array.
475 // We have to shift left 24 in order to flush out the 1's that appear
476 // when Java treats a value as negative that is cast from a byte to an int.
477 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
478 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
479 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
481 switch( numSigBytes )
484 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
485 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
486 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
487 destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
491 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
492 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
493 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
494 destination[ destOffset + 3 ] = EQUALS_SIGN;
498 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
499 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
500 destination[ destOffset + 2 ] = EQUALS_SIGN;
501 destination[ destOffset + 3 ] = EQUALS_SIGN;
512 * Serializes an object and returns the Base64-encoded
513 * version of that serialized object. If the object
514 * cannot be serialized or there is another error,
515 * the method will return <tt>null</tt>.
516 * The object is not GZip-compressed before being encoded.
518 * @param serializableObject The object to encode
519 * @return The Base64-encoded object
522 public static String encodeObject( java.io.Serializable serializableObject )
524 return encodeObject( serializableObject, NO_OPTIONS );
525 } // end encodeObject
530 * Serializes an object and returns the Base64-encoded
531 * version of that serialized object. If the object
532 * cannot be serialized or there is another error,
533 * the method will return <tt>null</tt>.
535 * Valid options:<pre>
536 * GZIP: gzip-compresses object before encoding it.
537 * DONT_BREAK_LINES: don't break lines at 76 characters
538 * <i>Note: Technically, this makes your encoding non-compliant.</i>
541 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
543 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
545 * @param serializableObject The object to encode
546 * @param options Specified options
547 * @return The Base64-encoded object
549 * @see Base64#DONT_BREAK_LINES
552 public static String encodeObject( java.io.Serializable serializableObject, int options )
555 java.io.ByteArrayOutputStream baos = null;
556 java.io.OutputStream b64os = null;
557 java.io.ObjectOutputStream oos = null;
558 java.util.zip.GZIPOutputStream gzos = null;
561 int gzip = (options & GZIP);
562 int dontBreakLines = (options & DONT_BREAK_LINES);
566 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
567 baos = new java.io.ByteArrayOutputStream();
568 b64os = new Base64.OutputStream( baos, ENCODE | options );
573 gzos = new java.util.zip.GZIPOutputStream( b64os );
574 oos = new java.io.ObjectOutputStream( gzos );
577 oos = new java.io.ObjectOutputStream( b64os );
579 oos.writeObject( serializableObject );
581 catch( java.io.IOException e )
588 try{ oos.close(); } catch( Exception e ){}
589 try{ gzos.close(); } catch( Exception e ){}
590 try{ b64os.close(); } catch( Exception e ){}
591 try{ baos.close(); } catch( Exception e ){}
594 // Return value according to relevant encoding.
597 return new String( baos.toByteArray(), PREFERRED_ENCODING );
599 catch (java.io.UnsupportedEncodingException uue)
601 return new String( baos.toByteArray() );
609 * Encodes a byte array into Base64 notation.
610 * Does not GZip-compress data.
612 * @param source The data to convert
615 public static String encodeBytes( byte[] source )
617 return encodeBytes( source, 0, source.length, NO_OPTIONS );
623 * Encodes a byte array into Base64 notation.
625 * Valid options:<pre>
626 * GZIP: gzip-compresses object before encoding it.
627 * DONT_BREAK_LINES: don't break lines at 76 characters
628 * <i>Note: Technically, this makes your encoding non-compliant.</i>
631 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
633 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
636 * @param source The data to convert
637 * @param options Specified options
639 * @see Base64#DONT_BREAK_LINES
642 public static String encodeBytes( byte[] source, int options )
644 return encodeBytes( source, 0, source.length, options );
649 * Encodes a byte array into Base64 notation.
650 * Does not GZip-compress data.
652 * @param source The data to convert
653 * @param off Offset in array where conversion should begin
654 * @param len Length of data to convert
657 public static String encodeBytes( byte[] source, int off, int len )
659 return encodeBytes( source, off, len, NO_OPTIONS );
665 * Encodes a byte array into Base64 notation.
667 * Valid options:<pre>
668 * GZIP: gzip-compresses object before encoding it.
669 * DONT_BREAK_LINES: don't break lines at 76 characters
670 * <i>Note: Technically, this makes your encoding non-compliant.</i>
673 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
675 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
678 * @param source The data to convert
679 * @param off Offset in array where conversion should begin
680 * @param len Length of data to convert
681 * @param options Specified options
682 * @param options alphabet type is pulled from this (standard, url-safe, ordered)
684 * @see Base64#DONT_BREAK_LINES
687 public static String encodeBytes( byte[] source, int off, int len, int options )
690 int dontBreakLines = ( options & DONT_BREAK_LINES );
691 int gzip = ( options & GZIP );
696 java.io.ByteArrayOutputStream baos = null;
697 java.util.zip.GZIPOutputStream gzos = null;
698 Base64.OutputStream b64os = null;
703 // GZip -> Base64 -> ByteArray
704 baos = new java.io.ByteArrayOutputStream();
705 b64os = new Base64.OutputStream( baos, ENCODE | options );
706 gzos = new java.util.zip.GZIPOutputStream( b64os );
708 gzos.write( source, off, len );
711 catch( java.io.IOException e )
718 try{ gzos.close(); } catch( Exception e ){}
719 try{ b64os.close(); } catch( Exception e ){}
720 try{ baos.close(); } catch( Exception e ){}
723 // Return value according to relevant encoding.
726 return new String( baos.toByteArray(), PREFERRED_ENCODING );
728 catch (java.io.UnsupportedEncodingException uue)
730 return new String( baos.toByteArray() );
732 } // end if: compress
734 // Else, don't compress. Better not to use streams at all then.
737 // Convert option to boolean in way that code likes it.
738 boolean breakLines = dontBreakLines == 0;
740 int len43 = len * 4 / 3;
741 byte[] outBuff = new byte[ ( len43 ) // Main 4:3
742 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
743 + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
748 for( ; d < len2; d+=3, e+=4 )
750 encode3to4( source, d+off, 3, outBuff, e, options );
753 if( breakLines && lineLength == MAX_LINE_LENGTH )
755 outBuff[e+4] = NEW_LINE;
758 } // end if: end of line
759 } // en dfor: each piece of array
763 encode3to4( source, d+off, len - d, outBuff, e, options );
765 } // end if: some padding needed
768 // Return value according to relevant encoding.
771 return new String( outBuff, 0, e, PREFERRED_ENCODING );
773 catch (java.io.UnsupportedEncodingException uue)
775 return new String( outBuff, 0, e );
778 } // end else: don't compress
786 /* ******** D E C O D I N G M E T H O D S ******** */
790 * Decodes four bytes from array <var>source</var>
791 * and writes the resulting bytes (up to three of them)
792 * to <var>destination</var>.
793 * The source and destination arrays can be manipulated
794 * anywhere along their length by specifying
795 * <var>srcOffset</var> and <var>destOffset</var>.
796 * This method does not check to make sure your arrays
797 * are large enough to accomodate <var>srcOffset</var> + 4 for
798 * the <var>source</var> array or <var>destOffset</var> + 3 for
799 * the <var>destination</var> array.
800 * This method returns the actual number of bytes that
801 * were converted from the Base64 encoding.
802 * <p>This is the lowest level of the decoding methods with
803 * all possible parameters.</p>
806 * @param source the array to convert
807 * @param srcOffset the index where conversion begins
808 * @param destination the array to hold the conversion
809 * @param destOffset the index where output will be put
810 * @param options alphabet type is pulled from this (standard, url-safe, ordered)
811 * @return the number of decoded bytes converted
814 private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options )
816 byte[] DECODABET = getDecodabet( options );
819 if( source[ srcOffset + 2] == EQUALS_SIGN )
821 // Two ways to do the same thing. Don't know which way I like best.
822 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
823 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
824 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
825 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
827 destination[ destOffset ] = (byte)( outBuff >>> 16 );
832 else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
834 // Two ways to do the same thing. Don't know which way I like best.
835 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
836 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
837 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
838 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
839 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
840 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
842 destination[ destOffset ] = (byte)( outBuff >>> 16 );
843 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
851 // Two ways to do the same thing. Don't know which way I like best.
852 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
853 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
854 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
855 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
856 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
857 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
858 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
859 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
862 destination[ destOffset ] = (byte)( outBuff >> 16 );
863 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
864 destination[ destOffset + 2 ] = (byte)( outBuff );
867 }catch( Exception e){
868 System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
869 System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
870 System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
871 System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
875 } // end decodeToBytes
881 * Very low-level access to decoding ASCII characters in
882 * the form of a byte array. Does not support automatically
883 * gunzipping or any other "fancy" features.
885 * @param source The Base64 encoded data
886 * @param off The offset of where to begin decoding
887 * @param len The length of characters to decode
888 * @return decoded data
891 public static byte[] decode( byte[] source, int off, int len, int options )
893 byte[] DECODABET = getDecodabet( options );
895 int len34 = len * 3 / 4;
896 byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
899 byte[] b4 = new byte[4];
904 for( i = off; i < off+len; i++ )
906 sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
907 sbiDecode = DECODABET[ sbiCrop ];
909 if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
911 if( sbiDecode >= EQUALS_SIGN_ENC )
913 b4[ b4Posn++ ] = sbiCrop;
916 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
919 // If that was the equals sign, break out of 'for' loop
920 if( sbiCrop == EQUALS_SIGN )
922 } // end if: quartet built
924 } // end if: equals sign or better
926 } // end if: white space, equals sign or better
929 System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
932 } // each input character
934 byte[] out = new byte[ outBuffPosn ];
935 System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
943 * Decodes data from Base64 notation, automatically
944 * detecting gzip-compressed data and decompressing it.
946 * @param s the string to decode
947 * @return the decoded data
950 public static byte[] decode( String s )
952 return decode( s, NO_OPTIONS );
957 * Decodes data from Base64 notation, automatically
958 * detecting gzip-compressed data and decompressing it.
960 * @param s the string to decode
961 * @param options encode options such as URL_SAFE
962 * @return the decoded data
965 public static byte[] decode( String s, int options )
970 bytes = s.getBytes( PREFERRED_ENCODING );
972 catch( java.io.UnsupportedEncodingException uee )
974 bytes = s.getBytes();
979 bytes = decode( bytes, 0, bytes.length, options );
982 // Check to see if it's gzip-compressed
983 // GZIP Magic Two-Byte Number: 0x8b1f (35615)
984 if( (options & NO_GZIP_MAGIC) == 0
985 && bytes != null && bytes.length >= 4 )
988 int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
989 if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
991 java.io.ByteArrayInputStream bais = null;
992 java.util.zip.GZIPInputStream gzis = null;
993 java.io.ByteArrayOutputStream baos = null;
994 byte[] buffer = new byte[2048];
999 baos = new java.io.ByteArrayOutputStream();
1000 bais = new java.io.ByteArrayInputStream( bytes );
1001 gzis = new java.util.zip.GZIPInputStream( bais );
1003 while( ( length = gzis.read( buffer ) ) >= 0 )
1005 baos.write(buffer,0,length);
1006 } // end while: reading input
1008 // No error? Get new bytes.
1009 bytes = baos.toByteArray();
1012 catch( java.io.IOException e )
1014 // Just return originally-decoded bytes
1018 try{ baos.close(); } catch( Exception e ){}
1019 try{ gzis.close(); } catch( Exception e ){}
1020 try{ bais.close(); } catch( Exception e ){}
1023 } // end if: gzipped
1024 } // end if: bytes.length >= 2
1033 * Attempts to decode Base64 data and deserialize a Java
1034 * Object within. Returns <tt>null</tt> if there was an error.
1036 * @param encodedObject The Base64 data to decode
1037 * @return The decoded and deserialized object
1040 public static Object decodeToObject( String encodedObject )
1042 // Decode and gunzip if necessary
1043 byte[] objBytes = decode( encodedObject );
1045 java.io.ByteArrayInputStream bais = null;
1046 java.io.ObjectInputStream ois = null;
1051 bais = new java.io.ByteArrayInputStream( objBytes );
1052 ois = new java.io.ObjectInputStream( bais );
1054 obj = ois.readObject();
1056 catch( java.io.IOException e )
1058 e.printStackTrace();
1061 catch( java.lang.ClassNotFoundException e )
1063 e.printStackTrace();
1068 try{ bais.close(); } catch( Exception e ){}
1069 try{ ois.close(); } catch( Exception e ){}
1073 } // end decodeObject
1078 * Convenience method for encoding data to a file.
1080 * @param dataToEncode byte array of data to encode in base64 form
1081 * @param filename Filename for saving encoded data
1082 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
1086 public static boolean encodeToFile( byte[] dataToEncode, String filename )
1088 boolean success = false;
1089 Base64.OutputStream bos = null;
1092 bos = new Base64.OutputStream(
1093 new java.io.FileOutputStream( filename ), Base64.ENCODE );
1094 bos.write( dataToEncode );
1097 catch( java.io.IOException e )
1101 } // end catch: IOException
1104 try{ bos.close(); } catch( Exception e ){}
1108 } // end encodeToFile
1112 * Convenience method for decoding data to a file.
1114 * @param dataToDecode Base64-encoded data as a string
1115 * @param filename Filename for saving decoded data
1116 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
1120 public static boolean decodeToFile( String dataToDecode, String filename )
1122 boolean success = false;
1123 Base64.OutputStream bos = null;
1126 bos = new Base64.OutputStream(
1127 new java.io.FileOutputStream( filename ), Base64.DECODE );
1128 bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
1131 catch( java.io.IOException e )
1134 } // end catch: IOException
1137 try{ bos.close(); } catch( Exception e ){}
1141 } // end decodeToFile
1147 * Convenience method for reading a base64-encoded
1148 * file and decoding it.
1150 * @param filename Filename for reading encoded data
1151 * @return decoded byte array or null if unsuccessful
1155 public static byte[] decodeFromFile( String filename )
1157 byte[] decodedData = null;
1158 Base64.InputStream bis = null;
1161 // Set up some useful variables
1162 java.io.File file = new java.io.File( filename );
1163 byte[] buffer = null;
1167 // Check for size of file
1168 if( file.length() > Integer.MAX_VALUE )
1170 System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
1172 } // end if: file too big for int index
1173 buffer = new byte[ (int)file.length() ];
1176 bis = new Base64.InputStream(
1177 new java.io.BufferedInputStream(
1178 new java.io.FileInputStream( file ) ), Base64.DECODE );
1181 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
1184 // Save in a variable to return
1185 decodedData = new byte[ length ];
1186 System.arraycopy( buffer, 0, decodedData, 0, length );
1189 catch( java.io.IOException e )
1191 System.err.println( "Error decoding from file " + filename );
1192 } // end catch: IOException
1195 try{ bis.close(); } catch( Exception e) {}
1199 } // end decodeFromFile
1204 * Convenience method for reading a binary file
1205 * and base64-encoding it.
1207 * @param filename Filename for reading binary data
1208 * @return base64-encoded string or null if unsuccessful
1212 public static String encodeFromFile( String filename )
1214 String encodedData = null;
1215 Base64.InputStream bis = null;
1218 // Set up some useful variables
1219 java.io.File file = new java.io.File( filename );
1220 byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)
1225 bis = new Base64.InputStream(
1226 new java.io.BufferedInputStream(
1227 new java.io.FileInputStream( file ) ), Base64.ENCODE );
1230 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
1233 // Save in a variable to return
1234 encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
1237 catch( java.io.IOException e )
1239 System.err.println( "Error encoding from file " + filename );
1240 } // end catch: IOException
1243 try{ bis.close(); } catch( Exception e) {}
1247 } // end encodeFromFile
1250 * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
1252 * @param infile Input file
1253 * @param outfile Output file
1256 public static void encodeFileToFile( String infile, String outfile )
1258 String encoded = Base64.encodeFromFile( infile );
1259 java.io.OutputStream out = null;
1261 out = new java.io.BufferedOutputStream(
1262 new java.io.FileOutputStream( outfile ) );
1263 out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
1265 catch( java.io.IOException ex ) {
1266 ex.printStackTrace();
1269 try { out.close(); }
1270 catch( Exception ex ){}
1272 } // end encodeFileToFile
1276 * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
1278 * @param infile Input file
1279 * @param outfile Output file
1282 public static void decodeFileToFile( String infile, String outfile )
1284 byte[] decoded = Base64.decodeFromFile( infile );
1285 java.io.OutputStream out = null;
1287 out = new java.io.BufferedOutputStream(
1288 new java.io.FileOutputStream( outfile ) );
1289 out.write( decoded );
1291 catch( java.io.IOException ex ) {
1292 ex.printStackTrace();
1295 try { out.close(); }
1296 catch( Exception ex ){}
1298 } // end decodeFileToFile
1301 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
1306 * A {@link Base64.InputStream} will read data from another
1307 * <tt>java.io.InputStream</tt>, given in the constructor,
1308 * and encode/decode to/from Base64 notation on the fly.
1313 public static class InputStream extends java.io.FilterInputStream
1315 private boolean encode; // Encoding or decoding
1316 private int position; // Current position in the buffer
1317 private byte[] buffer; // Small buffer holding converted data
1318 private int bufferLength; // Length of buffer (3 or 4)
1319 private int numSigBytes; // Number of meaningful bytes in the buffer
1320 private int lineLength;
1321 private boolean breakLines; // Break lines at less than 80 characters
1322 private int options; // Record options used to create the stream.
1323 private byte[] alphabet; // Local copies to avoid extra method calls
1324 private byte[] decodabet; // Local copies to avoid extra method calls
1328 * Constructs a {@link Base64.InputStream} in DECODE mode.
1330 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1333 public InputStream( java.io.InputStream in )
1336 } // end constructor
1340 * Constructs a {@link Base64.InputStream} in
1341 * either ENCODE or DECODE mode.
1343 * Valid options:<pre>
1344 * ENCODE or DECODE: Encode or Decode as data is read.
1345 * DONT_BREAK_LINES: don't break lines at 76 characters
1346 * (only meaningful when encoding)
1347 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1350 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
1353 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1354 * @param options Specified options
1355 * @see Base64#ENCODE
1356 * @see Base64#DECODE
1357 * @see Base64#DONT_BREAK_LINES
1360 public InputStream( java.io.InputStream in, int options )
1363 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1364 this.encode = (options & ENCODE) == ENCODE;
1365 this.bufferLength = encode ? 4 : 3;
1366 this.buffer = new byte[ bufferLength ];
1368 this.lineLength = 0;
1369 this.options = options; // Record for later, mostly to determine which alphabet to use
1370 this.alphabet = getAlphabet(options);
1371 this.decodabet = getDecodabet(options);
1372 } // end constructor
1375 * Reads enough of the input stream to convert
1376 * to/from Base64 and returns the next byte.
1381 public int read() throws java.io.IOException
1383 // Do we need to get data?
1388 byte[] b3 = new byte[3];
1389 int numBinaryBytes = 0;
1390 for( int i = 0; i < 3; i++ )
1396 // If end of stream, b is -1.
1401 } // end if: not end of stream
1404 catch( java.io.IOException e )
1406 // Only a problem if we got no data at all.
1411 } // end for: each needed input byte
1413 if( numBinaryBytes > 0 )
1415 encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
1418 } // end if: got data
1423 } // end if: encoding
1428 byte[] b4 = new byte[4];
1430 for( i = 0; i < 4; i++ )
1432 // Read four "meaningful" bytes:
1434 do{ b = in.read(); }
1435 while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
1438 break; // Reads a -1 if end of stream
1441 } // end for: each needed input byte
1445 numSigBytes = decode4to3( b4, 0, buffer, 0, options );
1447 } // end if: got four characters
1450 } // end else if: also padded correctly
1453 // Must have broken out from above.
1454 throw new java.io.IOException( "Improperly padded Base64 input." );
1457 } // end else: decode
1458 } // end else: get data
1463 // End of relevant data?
1464 if( /*!encode &&*/ position >= numSigBytes )
1467 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
1474 lineLength++; // This isn't important when decoding
1475 // but throwing an extra "if" seems
1476 // just as wasteful.
1478 int b = buffer[ position++ ];
1480 if( position >= bufferLength )
1483 return b & 0xFF; // This is how you "cast" a byte that's
1484 // intended to be unsigned.
1486 } // end if: position >= 0
1491 // When JDK1.4 is more accepted, use an assertion here.
1492 throw new java.io.IOException( "Error in Base64 code reading stream." );
1498 * Calls {@link #read()} repeatedly until the end of stream
1499 * is reached or <var>len</var> bytes are read.
1500 * Returns number of bytes read into array or -1 if
1501 * end of stream is encountered.
1503 * @param dest array to hold values
1504 * @param off offset for array
1505 * @param len max number of bytes to read into array
1506 * @return bytes read into array or -1 if end of stream is encountered.
1509 public int read( byte[] dest, int off, int len ) throws java.io.IOException
1513 for( i = 0; i < len; i++ )
1517 //if( b < 0 && i == 0 )
1521 dest[off + i] = (byte)b;
1525 break; // Out of 'for' loop
1526 } // end for: each byte read
1530 } // end inner class InputStream
1537 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
1542 * A {@link Base64.OutputStream} will write data to another
1543 * <tt>java.io.OutputStream</tt>, given in the constructor,
1544 * and encode/decode to/from Base64 notation on the fly.
1549 public static class OutputStream extends java.io.FilterOutputStream
1551 private boolean encode;
1552 private int position;
1553 private byte[] buffer;
1554 private int bufferLength;
1555 private int lineLength;
1556 private boolean breakLines;
1557 private byte[] b4; // Scratch used in a few places
1558 private boolean suspendEncoding;
1559 private int options; // Record for later
1560 private byte[] alphabet; // Local copies to avoid extra method calls
1561 private byte[] decodabet; // Local copies to avoid extra method calls
1564 * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1566 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1569 public OutputStream( java.io.OutputStream out )
1571 this( out, ENCODE );
1572 } // end constructor
1576 * Constructs a {@link Base64.OutputStream} in
1577 * either ENCODE or DECODE mode.
1579 * Valid options:<pre>
1580 * ENCODE or DECODE: Encode or Decode as data is read.
1581 * DONT_BREAK_LINES: don't break lines at 76 characters
1582 * (only meaningful when encoding)
1583 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1586 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
1588 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1589 * @param options Specified options.
1590 * @see Base64#ENCODE
1591 * @see Base64#DECODE
1592 * @see Base64#DONT_BREAK_LINES
1595 public OutputStream( java.io.OutputStream out, int options )
1598 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1599 this.encode = (options & ENCODE) == ENCODE;
1600 this.bufferLength = encode ? 3 : 4;
1601 this.buffer = new byte[ bufferLength ];
1603 this.lineLength = 0;
1604 this.suspendEncoding = false;
1605 this.b4 = new byte[4];
1606 this.options = options;
1607 this.alphabet = getAlphabet(options);
1608 this.decodabet = getDecodabet(options);
1609 } // end constructor
1613 * Writes the byte to the output stream after
1614 * converting to/from Base64 notation.
1615 * When encoding, bytes are buffered three
1616 * at a time before the output stream actually
1617 * gets a write() call.
1618 * When decoding, bytes are buffered four
1621 * @param theByte the byte to write
1624 public void write(int theByte) throws java.io.IOException
1626 // Encoding suspended?
1627 if( suspendEncoding )
1629 super.out.write( theByte );
1631 } // end if: supsended
1636 buffer[ position++ ] = (byte)theByte;
1637 if( position >= bufferLength ) // Enough to encode.
1639 out.write( encode3to4( b4, buffer, bufferLength, options ) );
1642 if( breakLines && lineLength >= MAX_LINE_LENGTH )
1644 out.write( NEW_LINE );
1646 } // end if: end of line
1649 } // end if: enough to output
1650 } // end if: encoding
1655 // Meaningful Base64 character?
1656 if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC )
1658 buffer[ position++ ] = (byte)theByte;
1659 if( position >= bufferLength ) // Enough to output.
1661 int len = Base64.decode4to3( buffer, 0, b4, 0, options );
1662 out.write( b4, 0, len );
1663 //out.write( Base64.decode4to3( buffer ) );
1665 } // end if: enough to output
1666 } // end if: meaningful base64 character
1667 else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC )
1669 throw new java.io.IOException( "Invalid character in Base64 data." );
1670 } // end else: not white space either
1671 } // end else: decoding
1677 * Calls {@link #write(int)} repeatedly until <var>len</var>
1678 * bytes are written.
1680 * @param theBytes array from which to read bytes
1681 * @param off offset for array
1682 * @param len max number of bytes to read into array
1685 public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
1687 // Encoding suspended?
1688 if( suspendEncoding )
1690 super.out.write( theBytes, off, len );
1692 } // end if: supsended
1694 for( int i = 0; i < len; i++ )
1696 write( theBytes[ off + i ] );
1697 } // end for: each byte written
1704 * Method added by PHIL. [Thanks, PHIL. -Rob]
1705 * This pads the buffer without closing the stream.
1707 public void flushBase64() throws java.io.IOException
1713 out.write( encode3to4( b4, buffer, position, options ) );
1715 } // end if: encoding
1718 throw new java.io.IOException( "Base64 input not properly padded." );
1719 } // end else: decoding
1720 } // end if: buffer partially full
1726 * Flushes and closes (I think, in the superclass) the stream.
1730 public void close() throws java.io.IOException
1732 // 1. Ensure that pending characters are written
1735 // 2. Actually close the stream
1736 // Base class both flushes and closes.
1746 * Suspends encoding of the stream.
1747 * May be helpful if you need to embed a piece of
1748 * base640-encoded data in a stream.
1752 public void suspendEncoding() throws java.io.IOException
1755 this.suspendEncoding = true;
1756 } // end suspendEncoding
1760 * Resumes encoding of the stream.
1761 * May be helpful if you need to embed a piece of
1762 * base640-encoded data in a stream.
1766 public void resumeEncoding()
1768 this.suspendEncoding = false;
1769 } // end resumeEncoding
1773 } // end inner class OutputStream
1776 } // end class Base64