Update deps to Funambol 8.7
[jgroupdav.git] / src / main / java / net / bionicmessage / extutils / Base64.java
blob3025a923e269739e1c92b3e41ac34b48a4f09479
1 package net.bionicmessage.extutils;
2 /**
3 * Encodes and decodes to and from Base64 notation.
5 * <p>
6 * Change Log:
7 * </p>
8 * <ul>
9 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
10 * some convenience methods for reading and writing to and from files.</li>
11 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
12 * with other encodings (like EBCDIC).</li>
13 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
14 * encoded data was a single byte.</li>
15 * <li>v2.0 - I got rid of methods that used booleans to set options.
16 * Now everything is more consolidated and cleaner. The code now detects
17 * when data that's being decoded is gzip-compressed and will decompress it
18 * automatically. Generally things are cleaner. You'll probably have to
19 * change some method calls that you were making to support the new
20 * options format (<tt>int</tt>s that you "OR" together).</li>
21 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
22 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
23 * Added the ability to "suspend" encoding in the Output Stream so
24 * you can turn on and off the encoding if you need to embed base64
25 * data in an otherwise "normal" stream (like an XML file).</li>
26 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
27 * This helps when using GZIP streams.
28 * Added the ability to GZip-compress objects before encoding them.</li>
29 * <li>v1.4 - Added helper methods to read/write files.</li>
30 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
31 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
32 * where last buffer being read, if not completely full, was not returned.</li>
33 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
34 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
35 * </ul>
37 * <p>
38 * I am placing this code in the Public Domain. Do with it as you will.
39 * This software comes with no guarantees or warranties but with
40 * plenty of well-wishing instead!
41 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
42 * periodically to check for updates or to contribute improvements.
43 * </p>
45 * @author Robert Harder
46 * @author rob@iharder.net
47 * @version 2.1
49 public class Base64
52 /* ******** P U B L I C F I E L D S ******** */
55 /** No options specified. Value is zero. */
56 public final static int NO_OPTIONS = 0;
58 /** Specify encoding. */
59 public final static int ENCODE = 1;
62 /** Specify decoding. */
63 public final static int DECODE = 0;
66 /** Specify that data should be gzip-compressed. */
67 public final static int GZIP = 2;
70 /** Don't break lines when encoding (violates strict Base64 specification) */
71 public final static int DONT_BREAK_LINES = 8;
74 /* ******** P R I V A T E F I E L D S ******** */
77 /** Maximum line length (76) of Base64 output. */
78 private final static int MAX_LINE_LENGTH = 76;
81 /** The equals sign (=) as a byte. */
82 private final static byte EQUALS_SIGN = (byte)'=';
85 /** The new line character (\n) as a byte. */
86 private final static byte NEW_LINE = (byte)'\n';
89 /** Preferred encoding. */
90 private final static String PREFERRED_ENCODING = "UTF-8";
93 /** The 64 valid Base64 values. */
94 private final static byte[] ALPHABET;
95 private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */
97 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
98 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
99 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
100 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
101 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
102 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
103 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
104 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
105 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
106 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
109 /** Determine which ALPHABET to use. */
110 static
112 byte[] __bytes;
115 __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING );
116 } // end try
117 catch (java.io.UnsupportedEncodingException use)
119 __bytes = _NATIVE_ALPHABET; // Fall back to native encoding
120 } // end catch
121 ALPHABET = __bytes;
122 } // end static
125 /**
126 * Translates a Base64 value to either its 6-bit reconstruction value
127 * or a negative number indicating some other meaning.
129 private final static byte[] DECODABET =
131 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
132 -5,-5, // Whitespace: Tab and Linefeed
133 -9,-9, // Decimal 11 - 12
134 -5, // Whitespace: Carriage Return
135 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
136 -9,-9,-9,-9,-9, // Decimal 27 - 31
137 -5, // Whitespace: Space
138 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
139 62, // Plus sign at decimal 43
140 -9,-9,-9, // Decimal 44 - 46
141 63, // Slash at decimal 47
142 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
143 -9,-9,-9, // Decimal 58 - 60
144 -1, // Equals sign at decimal 61
145 -9,-9,-9, // Decimal 62 - 64
146 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
147 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
148 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
149 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
150 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
151 -9,-9,-9,-9 // Decimal 123 - 126
152 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
153 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
154 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
155 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
156 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
157 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
158 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
159 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
160 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
161 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
164 // I think I end up not using the BAD_ENCODING indicator.
165 //private final static byte BAD_ENCODING = -9; // Indicates error in encoding
166 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
167 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
170 /** Defeats instantiation. */
171 private Base64(){}
175 /* ******** E N C O D I N G M E T H O D S ******** */
179 * Encodes up to the first three bytes of array <var>threeBytes</var>
180 * and returns a four-byte array in Base64 notation.
181 * The actual number of significant bytes in your array is
182 * given by <var>numSigBytes</var>.
183 * The array <var>threeBytes</var> needs only be as big as
184 * <var>numSigBytes</var>.
185 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
187 * @param b4 A reusable byte array to reduce array instantiation
188 * @param threeBytes the array to convert
189 * @param numSigBytes the number of significant bytes in your array
190 * @return four byte array in Base64 notation.
191 * @since 1.5.1
193 private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes )
195 encode3to4( threeBytes, 0, numSigBytes, b4, 0 );
196 return b4;
197 } // end encode3to4
201 * Encodes up to three bytes of the array <var>source</var>
202 * and writes the resulting four Base64 bytes to <var>destination</var>.
203 * The source and destination arrays can be manipulated
204 * anywhere along their length by specifying
205 * <var>srcOffset</var> and <var>destOffset</var>.
206 * This method does not check to make sure your arrays
207 * are large enough to accomodate <var>srcOffset</var> + 3 for
208 * the <var>source</var> array or <var>destOffset</var> + 4 for
209 * the <var>destination</var> array.
210 * The actual number of significant bytes in your array is
211 * given by <var>numSigBytes</var>.
213 * @param source the array to convert
214 * @param srcOffset the index where conversion begins
215 * @param numSigBytes the number of significant bytes in your array
216 * @param destination the array to hold the conversion
217 * @param destOffset the index where output will be put
218 * @return the <var>destination</var> array
219 * @since 1.3
221 private static byte[] encode3to4(
222 byte[] source, int srcOffset, int numSigBytes,
223 byte[] destination, int destOffset )
225 // 1 2 3
226 // 01234567890123456789012345678901 Bit position
227 // --------000000001111111122222222 Array position from threeBytes
228 // --------| || || || | Six bit groups to index ALPHABET
229 // >>18 >>12 >> 6 >> 0 Right shift necessary
230 // 0x3f 0x3f 0x3f Additional AND
232 // Create buffer with zero-padding if there are only one or two
233 // significant bytes passed in the array.
234 // We have to shift left 24 in order to flush out the 1's that appear
235 // when Java treats a value as negative that is cast from a byte to an int.
236 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
237 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
238 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
240 switch( numSigBytes )
242 case 3:
243 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
244 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
245 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
246 destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
247 return destination;
249 case 2:
250 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
251 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
252 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
253 destination[ destOffset + 3 ] = EQUALS_SIGN;
254 return destination;
256 case 1:
257 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
258 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
259 destination[ destOffset + 2 ] = EQUALS_SIGN;
260 destination[ destOffset + 3 ] = EQUALS_SIGN;
261 return destination;
263 default:
264 return destination;
265 } // end switch
266 } // end encode3to4
271 * Serializes an object and returns the Base64-encoded
272 * version of that serialized object. If the object
273 * cannot be serialized or there is another error,
274 * the method will return <tt>null</tt>.
275 * The object is not GZip-compressed before being encoded.
277 * @param serializableObject The object to encode
278 * @return The Base64-encoded object
279 * @since 1.4
281 public static String encodeObject( java.io.Serializable serializableObject )
283 return encodeObject( serializableObject, NO_OPTIONS );
284 } // end encodeObject
289 * Serializes an object and returns the Base64-encoded
290 * version of that serialized object. If the object
291 * cannot be serialized or there is another error,
292 * the method will return <tt>null</tt>.
293 * <p>
294 * Valid options:<pre>
295 * GZIP: gzip-compresses object before encoding it.
296 * DONT_BREAK_LINES: don't break lines at 76 characters
297 * <i>Note: Technically, this makes your encoding non-compliant.</i>
298 * </pre>
299 * <p>
300 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
301 * <p>
302 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
304 * @param serializableObject The object to encode
305 * @param options Specified options
306 * @return The Base64-encoded object
307 * @see Base64#GZIP
308 * @see Base64#DONT_BREAK_LINES
309 * @since 2.0
311 public static String encodeObject( java.io.Serializable serializableObject, int options )
313 // Streams
314 java.io.ByteArrayOutputStream baos = null;
315 java.io.OutputStream b64os = null;
316 java.io.ObjectOutputStream oos = null;
317 java.util.zip.GZIPOutputStream gzos = null;
319 // Isolate options
320 int gzip = (options & GZIP);
321 int dontBreakLines = (options & DONT_BREAK_LINES);
325 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
326 baos = new java.io.ByteArrayOutputStream();
327 b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
329 // GZip?
330 if( gzip == GZIP )
332 gzos = new java.util.zip.GZIPOutputStream( b64os );
333 oos = new java.io.ObjectOutputStream( gzos );
334 } // end if: gzip
335 else
336 oos = new java.io.ObjectOutputStream( b64os );
338 oos.writeObject( serializableObject );
339 } // end try
340 catch( java.io.IOException e )
342 e.printStackTrace();
343 return null;
344 } // end catch
345 finally
347 try{ oos.close(); } catch( Exception e ){}
348 try{ gzos.close(); } catch( Exception e ){}
349 try{ b64os.close(); } catch( Exception e ){}
350 try{ baos.close(); } catch( Exception e ){}
351 } // end finally
353 // Return value according to relevant encoding.
354 try
356 return new String( baos.toByteArray(), PREFERRED_ENCODING );
357 } // end try
358 catch (java.io.UnsupportedEncodingException uue)
360 return new String( baos.toByteArray() );
361 } // end catch
363 } // end encode
368 * Encodes a byte array into Base64 notation.
369 * Does not GZip-compress data.
371 * @param source The data to convert
372 * @since 1.4
374 public static String encodeBytes( byte[] source )
376 return encodeBytes( source, 0, source.length, NO_OPTIONS );
377 } // end encodeBytes
382 * Encodes a byte array into Base64 notation.
383 * <p>
384 * Valid options:<pre>
385 * GZIP: gzip-compresses object before encoding it.
386 * DONT_BREAK_LINES: don't break lines at 76 characters
387 * <i>Note: Technically, this makes your encoding non-compliant.</i>
388 * </pre>
389 * <p>
390 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
391 * <p>
392 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
395 * @param source The data to convert
396 * @param options Specified options
397 * @see Base64#GZIP
398 * @see Base64#DONT_BREAK_LINES
399 * @since 2.0
401 public static String encodeBytes( byte[] source, int options )
403 return encodeBytes( source, 0, source.length, options );
404 } // end encodeBytes
408 * Encodes a byte array into Base64 notation.
409 * Does not GZip-compress data.
411 * @param source The data to convert
412 * @param off Offset in array where conversion should begin
413 * @param len Length of data to convert
414 * @since 1.4
416 public static String encodeBytes( byte[] source, int off, int len )
418 return encodeBytes( source, off, len, NO_OPTIONS );
419 } // end encodeBytes
424 * Encodes a byte array into Base64 notation.
425 * <p>
426 * Valid options:<pre>
427 * GZIP: gzip-compresses object before encoding it.
428 * DONT_BREAK_LINES: don't break lines at 76 characters
429 * <i>Note: Technically, this makes your encoding non-compliant.</i>
430 * </pre>
431 * <p>
432 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
433 * <p>
434 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
437 * @param source The data to convert
438 * @param off Offset in array where conversion should begin
439 * @param len Length of data to convert
440 * @param options Specified options
441 * @see Base64#GZIP
442 * @see Base64#DONT_BREAK_LINES
443 * @since 2.0
445 public static String encodeBytes( byte[] source, int off, int len, int options )
447 // Isolate options
448 int dontBreakLines = ( options & DONT_BREAK_LINES );
449 int gzip = ( options & GZIP );
451 // Compress?
452 if( gzip == GZIP )
454 java.io.ByteArrayOutputStream baos = null;
455 java.util.zip.GZIPOutputStream gzos = null;
456 Base64.OutputStream b64os = null;
461 // GZip -> Base64 -> ByteArray
462 baos = new java.io.ByteArrayOutputStream();
463 b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
464 gzos = new java.util.zip.GZIPOutputStream( b64os );
466 gzos.write( source, off, len );
467 gzos.close();
468 } // end try
469 catch( java.io.IOException e )
471 e.printStackTrace();
472 return null;
473 } // end catch
474 finally
476 try{ gzos.close(); } catch( Exception e ){}
477 try{ b64os.close(); } catch( Exception e ){}
478 try{ baos.close(); } catch( Exception e ){}
479 } // end finally
481 // Return value according to relevant encoding.
484 return new String( baos.toByteArray(), PREFERRED_ENCODING );
485 } // end try
486 catch (java.io.UnsupportedEncodingException uue)
488 return new String( baos.toByteArray() );
489 } // end catch
490 } // end if: compress
492 // Else, don't compress. Better not to use streams at all then.
493 else
495 // Convert option to boolean in way that code likes it.
496 boolean breakLines = dontBreakLines == 0;
498 int len43 = len * 4 / 3;
499 byte[] outBuff = new byte[ ( len43 ) // Main 4:3
500 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
501 + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
502 int d = 0;
503 int e = 0;
504 int len2 = len - 2;
505 int lineLength = 0;
506 for( ; d < len2; d+=3, e+=4 )
508 encode3to4( source, d+off, 3, outBuff, e );
510 lineLength += 4;
511 if( breakLines && lineLength == MAX_LINE_LENGTH )
513 outBuff[e+4] = NEW_LINE;
514 e++;
515 lineLength = 0;
516 } // end if: end of line
517 } // en dfor: each piece of array
519 if( d < len )
521 encode3to4( source, d+off, len - d, outBuff, e );
522 e += 4;
523 } // end if: some padding needed
526 // Return value according to relevant encoding.
529 return new String( outBuff, 0, e, PREFERRED_ENCODING );
530 } // end try
531 catch (java.io.UnsupportedEncodingException uue)
533 return new String( outBuff, 0, e );
534 } // end catch
536 } // end else: don't compress
538 } // end encodeBytes
544 /* ******** D E C O D I N G M E T H O D S ******** */
548 * Decodes four bytes from array <var>source</var>
549 * and writes the resulting bytes (up to three of them)
550 * to <var>destination</var>.
551 * The source and destination arrays can be manipulated
552 * anywhere along their length by specifying
553 * <var>srcOffset</var> and <var>destOffset</var>.
554 * This method does not check to make sure your arrays
555 * are large enough to accomodate <var>srcOffset</var> + 4 for
556 * the <var>source</var> array or <var>destOffset</var> + 3 for
557 * the <var>destination</var> array.
558 * This method returns the actual number of bytes that
559 * were converted from the Base64 encoding.
562 * @param source the array to convert
563 * @param srcOffset the index where conversion begins
564 * @param destination the array to hold the conversion
565 * @param destOffset the index where output will be put
566 * @return the number of decoded bytes converted
567 * @since 1.3
569 private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset )
571 // Example: Dk==
572 if( source[ srcOffset + 2] == EQUALS_SIGN )
574 // Two ways to do the same thing. Don't know which way I like best.
575 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
576 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
577 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
578 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
580 destination[ destOffset ] = (byte)( outBuff >>> 16 );
581 return 1;
584 // Example: DkL=
585 else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
587 // Two ways to do the same thing. Don't know which way I like best.
588 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
589 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
590 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
591 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
592 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
593 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
595 destination[ destOffset ] = (byte)( outBuff >>> 16 );
596 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
597 return 2;
600 // Example: DkLE
601 else
603 try{
604 // Two ways to do the same thing. Don't know which way I like best.
605 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
606 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
607 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
608 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
609 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
610 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
611 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
612 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
615 destination[ destOffset ] = (byte)( outBuff >> 16 );
616 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
617 destination[ destOffset + 2 ] = (byte)( outBuff );
619 return 3;
620 }catch( Exception e){
621 System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
622 System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
623 System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
624 System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
625 return -1;
626 } //e nd catch
628 } // end decodeToBytes
634 * Very low-level access to decoding ASCII characters in
635 * the form of a byte array. Does not support automatically
636 * gunzipping or any other "fancy" features.
638 * @param source The Base64 encoded data
639 * @param off The offset of where to begin decoding
640 * @param len The length of characters to decode
641 * @return decoded data
642 * @since 1.3
644 public static byte[] decode( byte[] source, int off, int len )
646 int len34 = len * 3 / 4;
647 byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
648 int outBuffPosn = 0;
650 byte[] b4 = new byte[4];
651 int b4Posn = 0;
652 int i = 0;
653 byte sbiCrop = 0;
654 byte sbiDecode = 0;
655 for( i = off; i < off+len; i++ )
657 sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
658 sbiDecode = DECODABET[ sbiCrop ];
660 if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
662 if( sbiDecode >= EQUALS_SIGN_ENC )
664 b4[ b4Posn++ ] = sbiCrop;
665 if( b4Posn > 3 )
667 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
668 b4Posn = 0;
670 // If that was the equals sign, break out of 'for' loop
671 if( sbiCrop == EQUALS_SIGN )
672 break;
673 } // end if: quartet built
675 } // end if: equals sign or better
677 } // end if: white space, equals sign or better
678 else
680 System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
681 return null;
682 } // end else:
683 } // each input character
685 byte[] out = new byte[ outBuffPosn ];
686 System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
687 return out;
688 } // end decode
694 * Decodes data from Base64 notation, automatically
695 * detecting gzip-compressed data and decompressing it.
697 * @param s the string to decode
698 * @return the decoded data
699 * @since 1.4
701 public static byte[] decode( String s )
703 byte[] bytes;
706 bytes = s.getBytes( PREFERRED_ENCODING );
707 } // end try
708 catch( java.io.UnsupportedEncodingException uee )
710 bytes = s.getBytes();
711 } // end catch
712 //</change>
714 // Decode
715 bytes = decode( bytes, 0, bytes.length );
718 // Check to see if it's gzip-compressed
719 // GZIP Magic Two-Byte Number: 0x8b1f (35615)
720 if( bytes != null && bytes.length >= 4 )
723 int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
724 if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
726 java.io.ByteArrayInputStream bais = null;
727 java.util.zip.GZIPInputStream gzis = null;
728 java.io.ByteArrayOutputStream baos = null;
729 byte[] buffer = new byte[2048];
730 int length = 0;
734 baos = new java.io.ByteArrayOutputStream();
735 bais = new java.io.ByteArrayInputStream( bytes );
736 gzis = new java.util.zip.GZIPInputStream( bais );
738 while( ( length = gzis.read( buffer ) ) >= 0 )
740 baos.write(buffer,0,length);
741 } // end while: reading input
743 // No error? Get new bytes.
744 bytes = baos.toByteArray();
746 } // end try
747 catch( java.io.IOException e )
749 // Just return originally-decoded bytes
750 } // end catch
751 finally
753 try{ baos.close(); } catch( Exception e ){}
754 try{ gzis.close(); } catch( Exception e ){}
755 try{ bais.close(); } catch( Exception e ){}
756 } // end finally
758 } // end if: gzipped
759 } // end if: bytes.length >= 2
761 return bytes;
762 } // end decode
768 * Attempts to decode Base64 data and deserialize a Java
769 * Object within. Returns <tt>null</tt> if there was an error.
771 * @param encodedObject The Base64 data to decode
772 * @return The decoded and deserialized object
773 * @since 1.5
775 public static Object decodeToObject( String encodedObject )
777 // Decode and gunzip if necessary
778 byte[] objBytes = decode( encodedObject );
780 java.io.ByteArrayInputStream bais = null;
781 java.io.ObjectInputStream ois = null;
782 Object obj = null;
786 bais = new java.io.ByteArrayInputStream( objBytes );
787 ois = new java.io.ObjectInputStream( bais );
789 obj = ois.readObject();
790 } // end try
791 catch( java.io.IOException e )
793 e.printStackTrace();
794 obj = null;
795 } // end catch
796 catch( java.lang.ClassNotFoundException e )
798 e.printStackTrace();
799 obj = null;
800 } // end catch
801 finally
803 try{ bais.close(); } catch( Exception e ){}
804 try{ ois.close(); } catch( Exception e ){}
805 } // end finally
807 return obj;
808 } // end decodeObject
813 * Convenience method for encoding data to a file.
815 * @param dataToEncode byte array of data to encode in base64 form
816 * @param filename Filename for saving encoded data
817 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
819 * @since 2.1
821 public static boolean encodeToFile( byte[] dataToEncode, String filename )
823 boolean success = false;
824 Base64.OutputStream bos = null;
827 bos = new Base64.OutputStream(
828 new java.io.FileOutputStream( filename ), Base64.ENCODE );
829 bos.write( dataToEncode );
830 success = true;
831 } // end try
832 catch( java.io.IOException e )
835 success = false;
836 } // end catch: IOException
837 finally
839 try{ bos.close(); } catch( Exception e ){}
840 } // end finally
842 return success;
843 } // end encodeToFile
847 * Convenience method for decoding data to a file.
849 * @param dataToDecode Base64-encoded data as a string
850 * @param filename Filename for saving decoded data
851 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
853 * @since 2.1
855 public static boolean decodeToFile( String dataToDecode, String filename )
857 boolean success = false;
858 Base64.OutputStream bos = null;
861 bos = new Base64.OutputStream(
862 new java.io.FileOutputStream( filename ), Base64.DECODE );
863 bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
864 success = true;
865 } // end try
866 catch( java.io.IOException e )
868 success = false;
869 } // end catch: IOException
870 finally
872 try{ bos.close(); } catch( Exception e ){}
873 } // end finally
875 return success;
876 } // end decodeToFile
882 * Convenience method for reading a base64-encoded
883 * file and decoding it.
885 * @param filename Filename for reading encoded data
886 * @return decoded byte array or null if unsuccessful
888 * @since 2.1
890 public static byte[] decodeFromFile( String filename )
892 byte[] decodedData = null;
893 Base64.InputStream bis = null;
896 // Set up some useful variables
897 java.io.File file = new java.io.File( filename );
898 byte[] buffer = null;
899 int length = 0;
900 int numBytes = 0;
902 // Check for size of file
903 if( file.length() > Integer.MAX_VALUE )
905 System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
906 return null;
907 } // end if: file too big for int index
908 buffer = new byte[ (int)file.length() ];
910 // Open a stream
911 bis = new Base64.InputStream(
912 new java.io.BufferedInputStream(
913 new java.io.FileInputStream( file ) ), Base64.DECODE );
915 // Read until done
916 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
917 length += numBytes;
919 // Save in a variable to return
920 decodedData = new byte[ length ];
921 System.arraycopy( buffer, 0, decodedData, 0, length );
923 } // end try
924 catch( java.io.IOException e )
926 System.err.println( "Error decoding from file " + filename );
927 } // end catch: IOException
928 finally
930 try{ bis.close(); } catch( Exception e) {}
931 } // end finally
933 return decodedData;
934 } // end decodeFromFile
939 * Convenience method for reading a binary file
940 * and base64-encoding it.
942 * @param filename Filename for reading binary data
943 * @return base64-encoded string or null if unsuccessful
945 * @since 2.1
947 public static String encodeFromFile( String filename )
949 String encodedData = null;
950 Base64.InputStream bis = null;
953 // Set up some useful variables
954 java.io.File file = new java.io.File( filename );
955 byte[] buffer = new byte[ (int)(file.length() * 1.4) ];
956 int length = 0;
957 int numBytes = 0;
959 // Open a stream
960 bis = new Base64.InputStream(
961 new java.io.BufferedInputStream(
962 new java.io.FileInputStream( file ) ), Base64.ENCODE );
964 // Read until done
965 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
966 length += numBytes;
968 // Save in a variable to return
969 encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
971 } // end try
972 catch( java.io.IOException e )
974 System.err.println( "Error encoding from file " + filename );
975 } // end catch: IOException
976 finally
978 try{ bis.close(); } catch( Exception e) {}
979 } // end finally
981 return encodedData;
982 } // end encodeFromFile
987 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
992 * A {@link Base64.InputStream} will read data from another
993 * <tt>java.io.InputStream</tt>, given in the constructor,
994 * and encode/decode to/from Base64 notation on the fly.
996 * @see Base64
997 * @since 1.3
999 public static class InputStream extends java.io.FilterInputStream
1001 private boolean encode; // Encoding or decoding
1002 private int position; // Current position in the buffer
1003 private byte[] buffer; // Small buffer holding converted data
1004 private int bufferLength; // Length of buffer (3 or 4)
1005 private int numSigBytes; // Number of meaningful bytes in the buffer
1006 private int lineLength;
1007 private boolean breakLines; // Break lines at less than 80 characters
1011 * Constructs a {@link Base64.InputStream} in DECODE mode.
1013 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1014 * @since 1.3
1016 public InputStream( java.io.InputStream in )
1018 this( in, DECODE );
1019 } // end constructor
1023 * Constructs a {@link Base64.InputStream} in
1024 * either ENCODE or DECODE mode.
1025 * <p>
1026 * Valid options:<pre>
1027 * ENCODE or DECODE: Encode or Decode as data is read.
1028 * DONT_BREAK_LINES: don't break lines at 76 characters
1029 * (only meaningful when encoding)
1030 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1031 * </pre>
1032 * <p>
1033 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
1036 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1037 * @param options Specified options
1038 * @see Base64#ENCODE
1039 * @see Base64#DECODE
1040 * @see Base64#DONT_BREAK_LINES
1041 * @since 2.0
1043 public InputStream( java.io.InputStream in, int options )
1045 super( in );
1046 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1047 this.encode = (options & ENCODE) == ENCODE;
1048 this.bufferLength = encode ? 4 : 3;
1049 this.buffer = new byte[ bufferLength ];
1050 this.position = -1;
1051 this.lineLength = 0;
1052 } // end constructor
1055 * Reads enough of the input stream to convert
1056 * to/from Base64 and returns the next byte.
1058 * @return next byte
1059 * @since 1.3
1061 public int read() throws java.io.IOException
1063 // Do we need to get data?
1064 if( position < 0 )
1066 if( encode )
1068 byte[] b3 = new byte[3];
1069 int numBinaryBytes = 0;
1070 for( int i = 0; i < 3; i++ )
1074 int b = in.read();
1076 // If end of stream, b is -1.
1077 if( b >= 0 )
1079 b3[i] = (byte)b;
1080 numBinaryBytes++;
1081 } // end if: not end of stream
1083 } // end try: read
1084 catch( java.io.IOException e )
1086 // Only a problem if we got no data at all.
1087 if( i == 0 )
1088 throw e;
1090 } // end catch
1091 } // end for: each needed input byte
1093 if( numBinaryBytes > 0 )
1095 encode3to4( b3, 0, numBinaryBytes, buffer, 0 );
1096 position = 0;
1097 numSigBytes = 4;
1098 } // end if: got data
1099 else
1101 return -1;
1102 } // end else
1103 } // end if: encoding
1105 // Else decoding
1106 else
1108 byte[] b4 = new byte[4];
1109 int i = 0;
1110 for( i = 0; i < 4; i++ )
1112 // Read four "meaningful" bytes:
1113 int b = 0;
1114 do{ b = in.read(); }
1115 while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC );
1117 if( b < 0 )
1118 break; // Reads a -1 if end of stream
1120 b4[i] = (byte)b;
1121 } // end for: each needed input byte
1123 if( i == 4 )
1125 numSigBytes = decode4to3( b4, 0, buffer, 0 );
1126 position = 0;
1127 } // end if: got four characters
1128 else if( i == 0 ){
1129 return -1;
1130 } // end else if: also padded correctly
1131 else
1133 // Must have broken out from above.
1134 throw new java.io.IOException( "Improperly padded Base64 input." );
1135 } // end
1137 } // end else: decode
1138 } // end else: get data
1140 // Got data?
1141 if( position >= 0 )
1143 // End of relevant data?
1144 if( /*!encode &&*/ position >= numSigBytes )
1145 return -1;
1147 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
1149 lineLength = 0;
1150 return '\n';
1151 } // end if
1152 else
1154 lineLength++; // This isn't important when decoding
1155 // but throwing an extra "if" seems
1156 // just as wasteful.
1158 int b = buffer[ position++ ];
1160 if( position >= bufferLength )
1161 position = -1;
1163 return b & 0xFF; // This is how you "cast" a byte that's
1164 // intended to be unsigned.
1165 } // end else
1166 } // end if: position >= 0
1168 // Else error
1169 else
1171 // When JDK1.4 is more accepted, use an assertion here.
1172 throw new java.io.IOException( "Error in Base64 code reading stream." );
1173 } // end else
1174 } // end read
1178 * Calls {@link #read()} repeatedly until the end of stream
1179 * is reached or <var>len</var> bytes are read.
1180 * Returns number of bytes read into array or -1 if
1181 * end of stream is encountered.
1183 * @param dest array to hold values
1184 * @param off offset for array
1185 * @param len max number of bytes to read into array
1186 * @return bytes read into array or -1 if end of stream is encountered.
1187 * @since 1.3
1189 public int read( byte[] dest, int off, int len ) throws java.io.IOException
1191 int i;
1192 int b;
1193 for( i = 0; i < len; i++ )
1195 b = read();
1197 //if( b < 0 && i == 0 )
1198 // return -1;
1200 if( b >= 0 )
1201 dest[off + i] = (byte)b;
1202 else if( i == 0 )
1203 return -1;
1204 else
1205 break; // Out of 'for' loop
1206 } // end for: each byte read
1207 return i;
1208 } // end read
1210 } // end inner class InputStream
1217 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
1222 * A {@link Base64.OutputStream} will write data to another
1223 * <tt>java.io.OutputStream</tt>, given in the constructor,
1224 * and encode/decode to/from Base64 notation on the fly.
1226 * @see Base64
1227 * @since 1.3
1229 public static class OutputStream extends java.io.FilterOutputStream
1231 private boolean encode;
1232 private int position;
1233 private byte[] buffer;
1234 private int bufferLength;
1235 private int lineLength;
1236 private boolean breakLines;
1237 private byte[] b4; // Scratch used in a few places
1238 private boolean suspendEncoding;
1241 * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1243 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1244 * @since 1.3
1246 public OutputStream( java.io.OutputStream out )
1248 this( out, ENCODE );
1249 } // end constructor
1253 * Constructs a {@link Base64.OutputStream} in
1254 * either ENCODE or DECODE mode.
1255 * <p>
1256 * Valid options:<pre>
1257 * ENCODE or DECODE: Encode or Decode as data is read.
1258 * DONT_BREAK_LINES: don't break lines at 76 characters
1259 * (only meaningful when encoding)
1260 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1261 * </pre>
1262 * <p>
1263 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
1265 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1266 * @param options Specified options.
1267 * @see Base64#ENCODE
1268 * @see Base64#DECODE
1269 * @see Base64#DONT_BREAK_LINES
1270 * @since 1.3
1272 public OutputStream( java.io.OutputStream out, int options )
1274 super( out );
1275 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1276 this.encode = (options & ENCODE) == ENCODE;
1277 this.bufferLength = encode ? 3 : 4;
1278 this.buffer = new byte[ bufferLength ];
1279 this.position = 0;
1280 this.lineLength = 0;
1281 this.suspendEncoding = false;
1282 this.b4 = new byte[4];
1283 } // end constructor
1287 * Writes the byte to the output stream after
1288 * converting to/from Base64 notation.
1289 * When encoding, bytes are buffered three
1290 * at a time before the output stream actually
1291 * gets a write() call.
1292 * When decoding, bytes are buffered four
1293 * at a time.
1295 * @param theByte the byte to write
1296 * @since 1.3
1298 public void write(int theByte) throws java.io.IOException
1300 // Encoding suspended?
1301 if( suspendEncoding )
1303 super.out.write( theByte );
1304 return;
1305 } // end if: supsended
1307 // Encode?
1308 if( encode )
1310 buffer[ position++ ] = (byte)theByte;
1311 if( position >= bufferLength ) // Enough to encode.
1313 out.write( encode3to4( b4, buffer, bufferLength ) );
1315 lineLength += 4;
1316 if( breakLines && lineLength >= MAX_LINE_LENGTH )
1318 out.write( NEW_LINE );
1319 lineLength = 0;
1320 } // end if: end of line
1322 position = 0;
1323 } // end if: enough to output
1324 } // end if: encoding
1326 // Else, Decoding
1327 else
1329 // Meaningful Base64 character?
1330 if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC )
1332 buffer[ position++ ] = (byte)theByte;
1333 if( position >= bufferLength ) // Enough to output.
1335 int len = Base64.decode4to3( buffer, 0, b4, 0 );
1336 out.write( b4, 0, len );
1337 //out.write( Base64.decode4to3( buffer ) );
1338 position = 0;
1339 } // end if: enough to output
1340 } // end if: meaningful base64 character
1341 else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC )
1343 throw new java.io.IOException( "Invalid character in Base64 data." );
1344 } // end else: not white space either
1345 } // end else: decoding
1346 } // end write
1351 * Calls {@link #write(int)} repeatedly until <var>len</var>
1352 * bytes are written.
1354 * @param theBytes array from which to read bytes
1355 * @param off offset for array
1356 * @param len max number of bytes to read into array
1357 * @since 1.3
1359 public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
1361 // Encoding suspended?
1362 if( suspendEncoding )
1364 super.out.write( theBytes, off, len );
1365 return;
1366 } // end if: supsended
1368 for( int i = 0; i < len; i++ )
1370 write( theBytes[ off + i ] );
1371 } // end for: each byte written
1373 } // end write
1378 * Method added by PHIL. [Thanks, PHIL. -Rob]
1379 * This pads the buffer without closing the stream.
1381 public void flushBase64() throws java.io.IOException
1383 if( position > 0 )
1385 if( encode )
1387 out.write( encode3to4( b4, buffer, position ) );
1388 position = 0;
1389 } // end if: encoding
1390 else
1392 throw new java.io.IOException( "Base64 input not properly padded." );
1393 } // end else: decoding
1394 } // end if: buffer partially full
1396 } // end flush
1399 /**
1400 * Flushes and closes (I think, in the superclass) the stream.
1402 * @since 1.3
1404 public void close() throws java.io.IOException
1406 // 1. Ensure that pending characters are written
1407 flushBase64();
1409 // 2. Actually close the stream
1410 // Base class both flushes and closes.
1411 super.close();
1413 buffer = null;
1414 out = null;
1415 } // end close
1420 * Suspends encoding of the stream.
1421 * May be helpful if you need to embed a piece of
1422 * base640-encoded data in a stream.
1424 * @since 1.5.1
1426 public void suspendEncoding() throws java.io.IOException
1428 flushBase64();
1429 this.suspendEncoding = true;
1430 } // end suspendEncoding
1434 * Resumes encoding of the stream.
1435 * May be helpful if you need to embed a piece of
1436 * base640-encoded data in a stream.
1438 * @since 1.5.1
1440 public void resumeEncoding()
1442 this.suspendEncoding = false;
1443 } // end resumeEncoding
1447 } // end inner class OutputStream
1450 } // end class Base64