1 package org.codehaus.aspectwerkz.util;
2
3 /***
4 * Encodes and decodes to and from Base64 notation.
5 *
6 * <p>
7 * Change Log:
8 * </p>
9 * <ul>
10 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
11 * some convenience methods for reading and writing to and from files.</li>
12 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
13 * with other encodings (like EBCDIC).</li>
14 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
15 * encoded data was a single byte.</li>
16 * <li>v2.0 - I got rid of methods that used booleans to set options.
17 * Now everything is more consolidated and cleaner. The code now detects
18 * when data that's being decoded is gzip-compressed and will decompress it
19 * automatically. Generally things are cleaner. You'll probably have to
20 * change some method calls that you were making to support the new
21 * options format (<tt>int</tt>s that you "OR" together).</li>
22 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
23 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
24 * Added the ability to "suspend" encoding in the Output Stream so
25 * you can turn on and off the encoding if you need to embed base64
26 * data in an otherwise "normal" stream (like an XML file).</li>
27 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
28 * This helps when using GZIP streams.
29 * Added the ability to GZip-compress objects before encoding them.</li>
30 * <li>v1.4 - Added helper methods to read/write files.</li>
31 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
32 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
33 * where last buffer being read, if not completely full, was not returned.</li>
34 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
35 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
36 * </ul>
37 *
38 * <p>
39 * I am placing this code in the Public Domain. Do with it as you will.
40 * This software comes with no guarantees or warranties but with
41 * plenty of well-wishing instead!
42 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
43 * periodically to check for updates or to contribute improvements.
44 * </p>
45 *
46 * @author Robert Harder
47 * @author rob@iharder.net
48 * @version 2.1
49 */
50 public class Base64
51 {
52
53
54
55
56 /*** No options specified. Value is zero. */
57 public final static int NO_OPTIONS = 0;
58
59 /*** Specify encoding. */
60 public final static int ENCODE = 1;
61
62
63 /*** Specify decoding. */
64 public final static int DECODE = 0;
65
66
67 /*** Specify that data should be gzip-compressed. */
68 public final static int GZIP = 2;
69
70
71 /*** Don't break lines when encoding (violates strict Base64 specification) */
72 public final static int DONT_BREAK_LINES = 8;
73
74
75
76
77
78 /*** Maximum line length (76) of Base64 output. */
79 private final static int MAX_LINE_LENGTH = 76;
80
81
82 /*** The equals sign (=) as a byte. */
83 private final static byte EQUALS_SIGN = (byte)'=';
84
85
86 /*** The new line character (\n) as a byte. */
87 private final static byte NEW_LINE = (byte)'\n';
88
89
90 /*** Preferred encoding. */
91 private final static String PREFERRED_ENCODING = "UTF-8";
92
93
94 /*** The 64 valid Base64 values. */
95 private final static byte[] ALPHABET;
96 private final static byte[] _NATIVE_ALPHABET =
97 {
98 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
99 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
100 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
101 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
102 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
103 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
104 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
105 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
106 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
107 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
108 };
109
110 /*** Determine which ALPHABET to use. */
111 static
112 {
113 byte[] __bytes;
114 try
115 {
116 __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING );
117 }
118 catch (java.io.UnsupportedEncodingException use)
119 {
120 __bytes = _NATIVE_ALPHABET;
121 }
122 ALPHABET = __bytes;
123 }
124
125
126 /***
127 * Translates a Base64 value to either its 6-bit reconstruction value
128 * or a negative number indicating some other meaning.
129 **/
130 private final static byte[] DECODABET =
131 {
132 -9,-9,-9,-9,-9,-9,-9,-9,-9,
133 -5,-5,
134 -9,-9,
135 -5,
136 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,
137 -9,-9,-9,-9,-9,
138 -5,
139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,
140 62,
141 -9,-9,-9,
142 63,
143 52,53,54,55,56,57,58,59,60,61,
144 -9,-9,-9,
145 -1,
146 -9,-9,-9,
147 0,1,2,3,4,5,6,7,8,9,10,11,12,13,
148 14,15,16,17,18,19,20,21,22,23,24,25,
149 -9,-9,-9,-9,-9,-9,
150 26,27,28,29,30,31,32,33,34,35,36,37,38,
151 39,40,41,42,43,44,45,46,47,48,49,50,51,
152 -9,-9,-9,-9
153
154
155
156
157
158
159
160
161
162
163 };
164
165
166
167 private final static byte WHITE_SPACE_ENC = -5;
168 private final static byte EQUALS_SIGN_ENC = -1;
169
170
171 /*** Defeats instantiation. */
172 private Base64(){}
173
174
175
176
177
178
179 /***
180 * Encodes up to the first three bytes of array <var>threeBytes</var>
181 * and returns a four-byte array in Base64 notation.
182 * The actual number of significant bytes in your array is
183 * given by <var>numSigBytes</var>.
184 * The array <var>threeBytes</var> needs only be as big as
185 * <var>numSigBytes</var>.
186 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
187 *
188 * @param b4 A reusable byte array to reduce array instantiation
189 * @param threeBytes the array to convert
190 * @param numSigBytes the number of significant bytes in your array
191 * @return four byte array in Base64 notation.
192 * @since 1.5.1
193 */
194 private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes )
195 {
196 encode3to4( threeBytes, 0, numSigBytes, b4, 0 );
197 return b4;
198 }
199
200
201 /***
202 * Encodes up to three bytes of the array <var>source</var>
203 * and writes the resulting four Base64 bytes to <var>destination</var>.
204 * The source and destination arrays can be manipulated
205 * anywhere along their length by specifying
206 * <var>srcOffset</var> and <var>destOffset</var>.
207 * This method does not check to make sure your arrays
208 * are large enough to accomodate <var>srcOffset</var> + 3 for
209 * the <var>source</var> array or <var>destOffset</var> + 4 for
210 * the <var>destination</var> array.
211 * The actual number of significant bytes in your array is
212 * given by <var>numSigBytes</var>.
213 *
214 * @param source the array to convert
215 * @param srcOffset the index where conversion begins
216 * @param numSigBytes the number of significant bytes in your array
217 * @param destination the array to hold the conversion
218 * @param destOffset the index where output will be put
219 * @return the <var>destination</var> array
220 * @since 1.3
221 */
222 private static byte[] encode3to4(
223 byte[] source, int srcOffset, int numSigBytes,
224 byte[] destination, int destOffset )
225 {
226
227
228
229
230
231
232
233
234
235
236
237 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
238 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
239 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
240
241 switch( numSigBytes )
242 {
243 case 3:
244 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
245 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
246 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
247 destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
248 return destination;
249
250 case 2:
251 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
252 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
253 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
254 destination[ destOffset + 3 ] = EQUALS_SIGN;
255 return destination;
256
257 case 1:
258 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
259 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
260 destination[ destOffset + 2 ] = EQUALS_SIGN;
261 destination[ destOffset + 3 ] = EQUALS_SIGN;
262 return destination;
263
264 default:
265 return destination;
266 }
267 }
268
269
270
271 /***
272 * Serializes an object and returns the Base64-encoded
273 * version of that serialized object. If the object
274 * cannot be serialized or there is another error,
275 * the method will return <tt>null</tt>.
276 * The object is not GZip-compressed before being encoded.
277 *
278 * @param serializableObject The object to encode
279 * @return The Base64-encoded object
280 * @since 1.4
281 */
282 public static String encodeObject( java.io.Serializable serializableObject )
283 {
284 return encodeObject( serializableObject, NO_OPTIONS );
285 }
286
287
288
289 /***
290 * Serializes an object and returns the Base64-encoded
291 * version of that serialized object. If the object
292 * cannot be serialized or there is another error,
293 * the method will return <tt>null</tt>.
294 * <p>
295 * Valid options:<pre>
296 * GZIP: gzip-compresses object before encoding it.
297 * DONT_BREAK_LINES: don't break lines at 76 characters
298 * <i>Note: Technically, this makes your encoding non-compliant.</i>
299 * </pre>
300 * <p>
301 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
302 * <p>
303 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
304 *
305 * @param serializableObject The object to encode
306 * @param options Specified options
307 * @return The Base64-encoded object
308 * @see Base64#GZIP
309 * @see Base64#DONT_BREAK_LINES
310 * @since 2.0
311 */
312 public static String encodeObject( java.io.Serializable serializableObject, int options )
313 {
314
315 java.io.ByteArrayOutputStream baos = null;
316 java.io.OutputStream b64os = null;
317 java.io.ObjectOutputStream oos = null;
318 java.util.zip.GZIPOutputStream gzos = null;
319
320
321 int gzip = (options & GZIP);
322 int dontBreakLines = (options & DONT_BREAK_LINES);
323
324 try
325 {
326
327 baos = new java.io.ByteArrayOutputStream();
328 b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
329
330
331 if( gzip == GZIP )
332 {
333 gzos = new java.util.zip.GZIPOutputStream( b64os );
334 oos = new java.io.ObjectOutputStream( gzos );
335 }
336 else
337 oos = new java.io.ObjectOutputStream( b64os );
338
339 oos.writeObject( serializableObject );
340 }
341 catch( java.io.IOException e )
342 {
343 e.printStackTrace();
344 return null;
345 }
346 finally
347 {
348 try{ oos.close(); } catch( Exception e ){}
349 try{ gzos.close(); } catch( Exception e ){}
350 try{ b64os.close(); } catch( Exception e ){}
351 try{ baos.close(); } catch( Exception e ){}
352 }
353
354
355 try
356 {
357 return new String( baos.toByteArray(), PREFERRED_ENCODING );
358 }
359 catch (java.io.UnsupportedEncodingException uue)
360 {
361 return new String( baos.toByteArray() );
362 }
363
364 }
365
366
367
368 /***
369 * Encodes a byte array into Base64 notation.
370 * Does not GZip-compress data.
371 *
372 * @param source The data to convert
373 * @since 1.4
374 */
375 public static String encodeBytes( byte[] source )
376 {
377 return encodeBytes( source, 0, source.length, NO_OPTIONS );
378 }
379
380
381
382 /***
383 * Encodes a byte array into Base64 notation.
384 * <p>
385 * Valid options:<pre>
386 * GZIP: gzip-compresses object before encoding it.
387 * DONT_BREAK_LINES: don't break lines at 76 characters
388 * <i>Note: Technically, this makes your encoding non-compliant.</i>
389 * </pre>
390 * <p>
391 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
392 * <p>
393 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
394 *
395 *
396 * @param source The data to convert
397 * @param options Specified options
398 * @see Base64#GZIP
399 * @see Base64#DONT_BREAK_LINES
400 * @since 2.0
401 */
402 public static String encodeBytes( byte[] source, int options )
403 {
404 return encodeBytes( source, 0, source.length, options );
405 }
406
407
408 /***
409 * Encodes a byte array into Base64 notation.
410 * Does not GZip-compress data.
411 *
412 * @param source The data to convert
413 * @param off Offset in array where conversion should begin
414 * @param len Length of data to convert
415 * @since 1.4
416 */
417 public static String encodeBytes( byte[] source, int off, int len )
418 {
419 return encodeBytes( source, off, len, NO_OPTIONS );
420 }
421
422
423
424 /***
425 * Encodes a byte array into Base64 notation.
426 * <p>
427 * Valid options:<pre>
428 * GZIP: gzip-compresses object before encoding it.
429 * DONT_BREAK_LINES: don't break lines at 76 characters
430 * <i>Note: Technically, this makes your encoding non-compliant.</i>
431 * </pre>
432 * <p>
433 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
434 * <p>
435 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
436 *
437 *
438 * @param source The data to convert
439 * @param off Offset in array where conversion should begin
440 * @param len Length of data to convert
441 * @param options Specified options
442 * @see Base64#GZIP
443 * @see Base64#DONT_BREAK_LINES
444 * @since 2.0
445 */
446 public static String encodeBytes( byte[] source, int off, int len, int options )
447 {
448
449 int dontBreakLines = ( options & DONT_BREAK_LINES );
450 int gzip = ( options & GZIP );
451
452
453 if( gzip == GZIP )
454 {
455 java.io.ByteArrayOutputStream baos = null;
456 java.util.zip.GZIPOutputStream gzos = null;
457 Base64.OutputStream b64os = null;
458
459
460 try
461 {
462
463 baos = new java.io.ByteArrayOutputStream();
464 b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
465 gzos = new java.util.zip.GZIPOutputStream( b64os );
466
467 gzos.write( source, off, len );
468 gzos.close();
469 }
470 catch( java.io.IOException e )
471 {
472 e.printStackTrace();
473 return null;
474 }
475 finally
476 {
477 try{ gzos.close(); } catch( Exception e ){}
478 try{ b64os.close(); } catch( Exception e ){}
479 try{ baos.close(); } catch( Exception e ){}
480 }
481
482
483 try
484 {
485 return new String( baos.toByteArray(), PREFERRED_ENCODING );
486 }
487 catch (java.io.UnsupportedEncodingException uue)
488 {
489 return new String( baos.toByteArray() );
490 }
491 }
492
493
494 else
495 {
496
497 boolean breakLines = dontBreakLines == 0;
498
499 int len43 = len * 4 / 3;
500 byte[] outBuff = new byte[ ( len43 )
501 + ( (len % 3) > 0 ? 4 : 0 )
502 + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ];
503 int d = 0;
504 int e = 0;
505 int len2 = len - 2;
506 int lineLength = 0;
507 for( ; d < len2; d+=3, e+=4 )
508 {
509 encode3to4( source, d+off, 3, outBuff, e );
510
511 lineLength += 4;
512 if( breakLines && lineLength == MAX_LINE_LENGTH )
513 {
514 outBuff[e+4] = NEW_LINE;
515 e++;
516 lineLength = 0;
517 }
518 }
519
520 if( d < len )
521 {
522 encode3to4( source, d+off, len - d, outBuff, e );
523 e += 4;
524 }
525
526
527
528 try
529 {
530 return new String( outBuff, 0, e, PREFERRED_ENCODING );
531 }
532 catch (java.io.UnsupportedEncodingException uue)
533 {
534 return new String( outBuff, 0, e );
535 }
536
537 }
538
539 }
540
541
542
543
544
545
546
547
548 /***
549 * Decodes four bytes from array <var>source</var>
550 * and writes the resulting bytes (up to three of them)
551 * to <var>destination</var>.
552 * The source and destination arrays can be manipulated
553 * anywhere along their length by specifying
554 * <var>srcOffset</var> and <var>destOffset</var>.
555 * This method does not check to make sure your arrays
556 * are large enough to accomodate <var>srcOffset</var> + 4 for
557 * the <var>source</var> array or <var>destOffset</var> + 3 for
558 * the <var>destination</var> array.
559 * This method returns the actual number of bytes that
560 * were converted from the Base64 encoding.
561 *
562 *
563 * @param source the array to convert
564 * @param srcOffset the index where conversion begins
565 * @param destination the array to hold the conversion
566 * @param destOffset the index where output will be put
567 * @return the number of decoded bytes converted
568 * @since 1.3
569 */
570 private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset )
571 {
572
573 if( source[ srcOffset + 2] == EQUALS_SIGN )
574 {
575
576
577
578 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
579 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
580
581 destination[ destOffset ] = (byte)( outBuff >>> 16 );
582 return 1;
583 }
584
585
586 else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
587 {
588
589
590
591
592 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
593 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
594 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
595
596 destination[ destOffset ] = (byte)( outBuff >>> 16 );
597 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
598 return 2;
599 }
600
601
602 else
603 {
604 try{
605
606
607
608
609
610 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
611 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
612 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
613 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
614
615
616 destination[ destOffset ] = (byte)( outBuff >> 16 );
617 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
618 destination[ destOffset + 2 ] = (byte)( outBuff );
619
620 return 3;
621 }catch( Exception e){
622 System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
623 System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
624 System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
625 System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
626 return -1;
627 }
628 }
629 }
630
631
632
633
634 /***
635 * Very low-level access to decoding ASCII characters in
636 * the form of a byte array. Does not support automatically
637 * gunzipping or any other "fancy" features.
638 *
639 * @param source The Base64 encoded data
640 * @param off The offset of where to begin decoding
641 * @param len The length of characters to decode
642 * @return decoded data
643 * @since 1.3
644 */
645 public static byte[] decode( byte[] source, int off, int len )
646 {
647 int len34 = len * 3 / 4;
648 byte[] outBuff = new byte[ len34 ];
649 int outBuffPosn = 0;
650
651 byte[] b4 = new byte[4];
652 int b4Posn = 0;
653 int i = 0;
654 byte sbiCrop = 0;
655 byte sbiDecode = 0;
656 for( i = off; i < off+len; i++ )
657 {
658 sbiCrop = (byte)(source[i] & 0x7f);
659 sbiDecode = DECODABET[ sbiCrop ];
660
661 if( sbiDecode >= WHITE_SPACE_ENC )
662 {
663 if( sbiDecode >= EQUALS_SIGN_ENC )
664 {
665 b4[ b4Posn++ ] = sbiCrop;
666 if( b4Posn > 3 )
667 {
668 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
669 b4Posn = 0;
670
671
672 if( sbiCrop == EQUALS_SIGN )
673 break;
674 }
675
676 }
677
678 }
679 else
680 {
681 System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
682 return null;
683 }
684 }
685
686 byte[] out = new byte[ outBuffPosn ];
687 System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
688 return out;
689 }
690
691
692
693
694 /***
695 * Decodes data from Base64 notation, automatically
696 * detecting gzip-compressed data and decompressing it.
697 *
698 * @param s the string to decode
699 * @return the decoded data
700 * @since 1.4
701 */
702 public static byte[] decode( String s )
703 {
704 byte[] bytes;
705 try
706 {
707 bytes = s.getBytes( PREFERRED_ENCODING );
708 }
709 catch( java.io.UnsupportedEncodingException uee )
710 {
711 bytes = s.getBytes();
712 }
713
714
715
716 bytes = decode( bytes, 0, bytes.length );
717
718
719
720
721 if( bytes != null && bytes.length >= 4 )
722 {
723
724 int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
725 if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
726 {
727 java.io.ByteArrayInputStream bais = null;
728 java.util.zip.GZIPInputStream gzis = null;
729 java.io.ByteArrayOutputStream baos = null;
730 byte[] buffer = new byte[2048];
731 int length = 0;
732
733 try
734 {
735 baos = new java.io.ByteArrayOutputStream();
736 bais = new java.io.ByteArrayInputStream( bytes );
737 gzis = new java.util.zip.GZIPInputStream( bais );
738
739 while( ( length = gzis.read( buffer ) ) >= 0 )
740 {
741 baos.write(buffer,0,length);
742 }
743
744
745 bytes = baos.toByteArray();
746
747 }
748 catch( java.io.IOException e )
749 {
750
751 }
752 finally
753 {
754 try{ baos.close(); } catch( Exception e ){}
755 try{ gzis.close(); } catch( Exception e ){}
756 try{ bais.close(); } catch( Exception e ){}
757 }
758
759 }
760 }
761
762 return bytes;
763 }
764
765
766
767
768 /***
769 * Attempts to decode Base64 data and deserialize a Java
770 * Object within. Returns <tt>null</tt> if there was an error.
771 *
772 * @param encodedObject The Base64 data to decode
773 * @return The decoded and deserialized object
774 * @since 1.5
775 */
776 public static Object decodeToObject( String encodedObject )
777 {
778
779 byte[] objBytes = decode( encodedObject );
780
781 java.io.ByteArrayInputStream bais = null;
782 java.io.ObjectInputStream ois = null;
783 Object obj = null;
784
785 try
786 {
787 bais = new java.io.ByteArrayInputStream( objBytes );
788 ois = new java.io.ObjectInputStream( bais );
789
790 obj = ois.readObject();
791 }
792 catch( java.io.IOException e )
793 {
794 e.printStackTrace();
795 obj = null;
796 }
797 catch( java.lang.ClassNotFoundException e )
798 {
799 e.printStackTrace();
800 obj = null;
801 }
802 finally
803 {
804 try{ bais.close(); } catch( Exception e ){}
805 try{ ois.close(); } catch( Exception e ){}
806 }
807
808 return obj;
809 }
810
811
812
813 /***
814 * Convenience method for encoding data to a file.
815 *
816 * @param dataToEncode byte array of data to encode in base64 form
817 * @param filename Filename for saving encoded data
818 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
819 *
820 * @since 2.1
821 */
822 public static boolean encodeToFile( byte[] dataToEncode, String filename )
823 {
824 boolean success = false;
825 Base64.OutputStream bos = null;
826 try
827 {
828 bos = new Base64.OutputStream(
829 new java.io.FileOutputStream( filename ), Base64.ENCODE );
830 bos.write( dataToEncode );
831 success = true;
832 }
833 catch( java.io.IOException e )
834 {
835
836 success = false;
837 }
838 finally
839 {
840 try{ bos.close(); } catch( Exception e ){}
841 }
842
843 return success;
844 }
845
846
847 /***
848 * Convenience method for decoding data to a file.
849 *
850 * @param dataToDecode Base64-encoded data as a string
851 * @param filename Filename for saving decoded data
852 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
853 *
854 * @since 2.1
855 */
856 public static boolean decodeToFile( String dataToDecode, String filename )
857 {
858 boolean success = false;
859 Base64.OutputStream bos = null;
860 try
861 {
862 bos = new Base64.OutputStream(
863 new java.io.FileOutputStream( filename ), Base64.DECODE );
864 bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
865 success = true;
866 }
867 catch( java.io.IOException e )
868 {
869 success = false;
870 }
871 finally
872 {
873 try{ bos.close(); } catch( Exception e ){}
874 }
875
876 return success;
877 }
878
879
880
881
882 /***
883 * Convenience method for reading a base64-encoded
884 * file and decoding it.
885 *
886 * @param filename Filename for reading encoded data
887 * @return decoded byte array or null if unsuccessful
888 *
889 * @since 2.1
890 */
891 public static byte[] decodeFromFile( String filename )
892 {
893 byte[] decodedData = null;
894 Base64.InputStream bis = null;
895 try
896 {
897
898 java.io.File file = new java.io.File( filename );
899 byte[] buffer = null;
900 int length = 0;
901 int numBytes = 0;
902
903
904 if( file.length() > Integer.MAX_VALUE )
905 {
906 System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
907 return null;
908 }
909 buffer = new byte[ (int)file.length() ];
910
911
912 bis = new Base64.InputStream(
913 new java.io.BufferedInputStream(
914 new java.io.FileInputStream( file ) ), Base64.DECODE );
915
916
917 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
918 length += numBytes;
919
920
921 decodedData = new byte[ length ];
922 System.arraycopy( buffer, 0, decodedData, 0, length );
923
924 }
925 catch( java.io.IOException e )
926 {
927 System.err.println( "Error decoding from file " + filename );
928 }
929 finally
930 {
931 try{ bis.close(); } catch( Exception e) {}
932 }
933
934 return decodedData;
935 }
936
937
938
939 /***
940 * Convenience method for reading a binary file
941 * and base64-encoding it.
942 *
943 * @param filename Filename for reading binary data
944 * @return base64-encoded string or null if unsuccessful
945 *
946 * @since 2.1
947 */
948 public static String encodeFromFile( String filename )
949 {
950 String encodedData = null;
951 Base64.InputStream bis = null;
952 try
953 {
954
955 java.io.File file = new java.io.File( filename );
956 byte[] buffer = new byte[ (int)(file.length() * 1.4) ];
957 int length = 0;
958 int numBytes = 0;
959
960
961 bis = new Base64.InputStream(
962 new java.io.BufferedInputStream(
963 new java.io.FileInputStream( file ) ), Base64.ENCODE );
964
965
966 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
967 length += numBytes;
968
969
970 encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
971
972 }
973 catch( java.io.IOException e )
974 {
975 System.err.println( "Error encoding from file " + filename );
976 }
977 finally
978 {
979 try{ bis.close(); } catch( Exception e) {}
980 }
981
982 return encodedData;
983 }
984
985
986
987
988
989
990
991
992 /***
993 * A {@link Base64.InputStream} will read data from another
994 * <tt>java.io.InputStream</tt>, given in the constructor,
995 * and encode/decode to/from Base64 notation on the fly.
996 *
997 * @see Base64
998 * @since 1.3
999 */
1000 public static class InputStream extends java.io.FilterInputStream
1001 {
1002 private boolean encode;
1003 private int position;
1004 private byte[] buffer;
1005 private int bufferLength;
1006 private int numSigBytes;
1007 private int lineLength;
1008 private boolean breakLines;
1009
1010
1011 /***
1012 * Constructs a {@link Base64.InputStream} in DECODE mode.
1013 *
1014 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1015 * @since 1.3
1016 */
1017 public InputStream( java.io.InputStream in )
1018 {
1019 this( in, DECODE );
1020 }
1021
1022
1023 /***
1024 * Constructs a {@link Base64.InputStream} in
1025 * either ENCODE or DECODE mode.
1026 * <p>
1027 * Valid options:<pre>
1028 * ENCODE or DECODE: Encode or Decode as data is read.
1029 * DONT_BREAK_LINES: don't break lines at 76 characters
1030 * (only meaningful when encoding)
1031 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1032 * </pre>
1033 * <p>
1034 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
1035 *
1036 *
1037 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1038 * @param options Specified options
1039 * @see Base64#ENCODE
1040 * @see Base64#DECODE
1041 * @see Base64#DONT_BREAK_LINES
1042 * @since 2.0
1043 */
1044 public InputStream( java.io.InputStream in, int options )
1045 {
1046 super( in );
1047 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1048 this.encode = (options & ENCODE) == ENCODE;
1049 this.bufferLength = encode ? 4 : 3;
1050 this.buffer = new byte[ bufferLength ];
1051 this.position = -1;
1052 this.lineLength = 0;
1053 }
1054
1055 /***
1056 * Reads enough of the input stream to convert
1057 * to/from Base64 and returns the next byte.
1058 *
1059 * @return next byte
1060 * @since 1.3
1061 */
1062 public int read() throws java.io.IOException
1063 {
1064
1065 if( position < 0 )
1066 {
1067 if( encode )
1068 {
1069 byte[] b3 = new byte[3];
1070 int numBinaryBytes = 0;
1071 for( int i = 0; i < 3; i++ )
1072 {
1073 try
1074 {
1075 int b = in.read();
1076
1077
1078 if( b >= 0 )
1079 {
1080 b3[i] = (byte)b;
1081 numBinaryBytes++;
1082 }
1083
1084 }
1085 catch( java.io.IOException e )
1086 {
1087
1088 if( i == 0 )
1089 throw e;
1090
1091 }
1092 }
1093
1094 if( numBinaryBytes > 0 )
1095 {
1096 encode3to4( b3, 0, numBinaryBytes, buffer, 0 );
1097 position = 0;
1098 numSigBytes = 4;
1099 }
1100 else
1101 {
1102 return -1;
1103 }
1104 }
1105
1106
1107 else
1108 {
1109 byte[] b4 = new byte[4];
1110 int i = 0;
1111 for( i = 0; i < 4; i++ )
1112 {
1113
1114 int b = 0;
1115 do{ b = in.read(); }
1116 while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC );
1117
1118 if( b < 0 )
1119 break;
1120
1121 b4[i] = (byte)b;
1122 }
1123
1124 if( i == 4 )
1125 {
1126 numSigBytes = decode4to3( b4, 0, buffer, 0 );
1127 position = 0;
1128 }
1129 else if( i == 0 ){
1130 return -1;
1131 }
1132 else
1133 {
1134
1135 throw new java.io.IOException( "Improperly padded Base64 input." );
1136 }
1137
1138 }
1139 }
1140
1141
1142 if( position >= 0 )
1143 {
1144
1145 if(
1146 return -1;
1147
1148 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
1149 {
1150 lineLength = 0;
1151 return '\n';
1152 }
1153 else
1154 {
1155 lineLength++;
1156
1157
1158
1159 int b = buffer[ position++ ];
1160
1161 if( position >= bufferLength )
1162 position = -1;
1163
1164 return b & 0xFF;
1165
1166 }
1167 }
1168
1169
1170 else
1171 {
1172
1173 throw new java.io.IOException( "Error in Base64 code reading stream." );
1174 }
1175 }
1176
1177
1178 /***
1179 * Calls {@link #read()} repeatedly until the end of stream
1180 * is reached or <var>len</var> bytes are read.
1181 * Returns number of bytes read into array or -1 if
1182 * end of stream is encountered.
1183 *
1184 * @param dest array to hold values
1185 * @param off offset for array
1186 * @param len max number of bytes to read into array
1187 * @return bytes read into array or -1 if end of stream is encountered.
1188 * @since 1.3
1189 */
1190 public int read( byte[] dest, int off, int len ) throws java.io.IOException
1191 {
1192 int i;
1193 int b;
1194 for( i = 0; i < len; i++ )
1195 {
1196 b = read();
1197
1198
1199
1200
1201 if( b >= 0 )
1202 dest[off + i] = (byte)b;
1203 else if( i == 0 )
1204 return -1;
1205 else
1206 break;
1207 }
1208 return i;
1209 }
1210
1211 }
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222 /***
1223 * A {@link Base64.OutputStream} will write data to another
1224 * <tt>java.io.OutputStream</tt>, given in the constructor,
1225 * and encode/decode to/from Base64 notation on the fly.
1226 *
1227 * @see Base64
1228 * @since 1.3
1229 */
1230 public static class OutputStream extends java.io.FilterOutputStream
1231 {
1232 private boolean encode;
1233 private int position;
1234 private byte[] buffer;
1235 private int bufferLength;
1236 private int lineLength;
1237 private boolean breakLines;
1238 private byte[] b4;
1239 private boolean suspendEncoding;
1240
1241 /***
1242 * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1243 *
1244 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1245 * @since 1.3
1246 */
1247 public OutputStream( java.io.OutputStream out )
1248 {
1249 this( out, ENCODE );
1250 }
1251
1252
1253 /***
1254 * Constructs a {@link Base64.OutputStream} in
1255 * either ENCODE or DECODE mode.
1256 * <p>
1257 * Valid options:<pre>
1258 * ENCODE or DECODE: Encode or Decode as data is read.
1259 * DONT_BREAK_LINES: don't break lines at 76 characters
1260 * (only meaningful when encoding)
1261 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1262 * </pre>
1263 * <p>
1264 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
1265 *
1266 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1267 * @param options Specified options.
1268 * @see Base64#ENCODE
1269 * @see Base64#DECODE
1270 * @see Base64#DONT_BREAK_LINES
1271 * @since 1.3
1272 */
1273 public OutputStream( java.io.OutputStream out, int options )
1274 {
1275 super( out );
1276 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1277 this.encode = (options & ENCODE) == ENCODE;
1278 this.bufferLength = encode ? 3 : 4;
1279 this.buffer = new byte[ bufferLength ];
1280 this.position = 0;
1281 this.lineLength = 0;
1282 this.suspendEncoding = false;
1283 this.b4 = new byte[4];
1284 }
1285
1286
1287 /***
1288 * Writes the byte to the output stream after
1289 * converting to/from Base64 notation.
1290 * When encoding, bytes are buffered three
1291 * at a time before the output stream actually
1292 * gets a write() call.
1293 * When decoding, bytes are buffered four
1294 * at a time.
1295 *
1296 * @param theByte the byte to write
1297 * @since 1.3
1298 */
1299 public void write(int theByte) throws java.io.IOException
1300 {
1301
1302 if( suspendEncoding )
1303 {
1304 super.out.write( theByte );
1305 return;
1306 }
1307
1308
1309 if( encode )
1310 {
1311 buffer[ position++ ] = (byte)theByte;
1312 if( position >= bufferLength )
1313 {
1314 out.write( encode3to4( b4, buffer, bufferLength ) );
1315
1316 lineLength += 4;
1317 if( breakLines && lineLength >= MAX_LINE_LENGTH )
1318 {
1319 out.write( NEW_LINE );
1320 lineLength = 0;
1321 }
1322
1323 position = 0;
1324 }
1325 }
1326
1327
1328 else
1329 {
1330
1331 if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC )
1332 {
1333 buffer[ position++ ] = (byte)theByte;
1334 if( position >= bufferLength )
1335 {
1336 int len = Base64.decode4to3( buffer, 0, b4, 0 );
1337 out.write( b4, 0, len );
1338
1339 position = 0;
1340 }
1341 }
1342 else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC )
1343 {
1344 throw new java.io.IOException( "Invalid character in Base64 data." );
1345 }
1346 }
1347 }
1348
1349
1350
1351 /***
1352 * Calls {@link #write(int)} repeatedly until <var>len</var>
1353 * bytes are written.
1354 *
1355 * @param theBytes array from which to read bytes
1356 * @param off offset for array
1357 * @param len max number of bytes to read into array
1358 * @since 1.3
1359 */
1360 public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
1361 {
1362
1363 if( suspendEncoding )
1364 {
1365 super.out.write( theBytes, off, len );
1366 return;
1367 }
1368
1369 for( int i = 0; i < len; i++ )
1370 {
1371 write( theBytes[ off + i ] );
1372 }
1373
1374 }
1375
1376
1377
1378 /***
1379 * Method added by PHIL. [Thanks, PHIL. -Rob]
1380 * This pads the buffer without closing the stream.
1381 */
1382 public void flushBase64() throws java.io.IOException
1383 {
1384 if( position > 0 )
1385 {
1386 if( encode )
1387 {
1388 out.write( encode3to4( b4, buffer, position ) );
1389 position = 0;
1390 }
1391 else
1392 {
1393 throw new java.io.IOException( "Base64 input not properly padded." );
1394 }
1395 }
1396
1397 }
1398
1399
1400 /***
1401 * Flushes and closes (I think, in the superclass) the stream.
1402 *
1403 * @since 1.3
1404 */
1405 public void close() throws java.io.IOException
1406 {
1407
1408 flushBase64();
1409
1410
1411
1412 super.close();
1413
1414 buffer = null;
1415 out = null;
1416 }
1417
1418
1419
1420 /***
1421 * Suspends encoding of the stream.
1422 * May be helpful if you need to embed a piece of
1423 * base640-encoded data in a stream.
1424 *
1425 * @since 1.5.1
1426 */
1427 public void suspendEncoding() throws java.io.IOException
1428 {
1429 flushBase64();
1430 this.suspendEncoding = true;
1431 }
1432
1433
1434 /***
1435 * Resumes encoding of the stream.
1436 * May be helpful if you need to embed a piece of
1437 * base640-encoded data in a stream.
1438 *
1439 * @since 1.5.1
1440 */
1441 public void resumeEncoding()
1442 {
1443 this.suspendEncoding = false;
1444 }
1445
1446
1447
1448 }
1449
1450
1451 }