KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > util > Base64


1 package org.alfresco.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 /* ******** P U B L I C F I E L D S ******** */
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 /* ******** P R I V A T E F I E L D S ******** */
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 JavaDoc 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 = /* May be something funny like EBCDIC */
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         } // end try
118
catch (java.io.UnsupportedEncodingException JavaDoc use)
119         {
120             __bytes = _NATIVE_ALPHABET; // Fall back to native encoding
121
} // end catch
122
ALPHABET = __bytes;
123     } // end static
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, // Decimal 0 - 8
133
-5,-5, // Whitespace: Tab and Linefeed
134
-9,-9, // Decimal 11 - 12
135
-5, // Whitespace: Carriage Return
136
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
137
-9,-9,-9,-9,-9, // Decimal 27 - 31
138
-5, // Whitespace: Space
139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
140
62, // Plus sign at decimal 43
141
-9,-9,-9, // Decimal 44 - 46
142
63, // Slash at decimal 47
143
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
144
-9,-9,-9, // Decimal 58 - 60
145
-1, // Equals sign at decimal 61
146
-9,-9,-9, // Decimal 62 - 64
147
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
148
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
149
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
150
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
151
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
152
-9,-9,-9,-9 // Decimal 123 - 126
153
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
154         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
155         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
156         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
157         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
158         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
159         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
160         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
161         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
162         -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */

163     };
164     
165     // I think I end up not using the BAD_ENCODING indicator.
166
//private final static byte BAD_ENCODING = -9; // Indicates error in encoding
167
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
168
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
169

170     
171     /** Defeats instantiation. */
172     private Base64(){}
173     
174     
175     
176 /* ******** E N C O D I N G M E T H O D S ******** */
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     } // end encode3to4
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         // 1 2 3
227
// 01234567890123456789012345678901 Bit position
228
// --------000000001111111122222222 Array position from threeBytes
229
// --------| || || || | Six bit groups to index ALPHABET
230
// >>18 >>12 >> 6 >> 0 Right shift necessary
231
// 0x3f 0x3f 0x3f Additional AND
232

233         // Create buffer with zero-padding if there are only one or two
234
// significant bytes passed in the array.
235
// We have to shift left 24 in order to flush out the 1's that appear
236
// when Java treats a value as negative that is cast from a byte to an int.
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         } // end switch
267
} // end encode3to4
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 JavaDoc encodeObject( java.io.Serializable JavaDoc serializableObject )
283     {
284         return encodeObject( serializableObject, NO_OPTIONS );
285     } // end encodeObject
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 JavaDoc encodeObject( java.io.Serializable JavaDoc serializableObject, int options )
313     {
314         // Streams
315
java.io.ByteArrayOutputStream JavaDoc baos = null;
316         java.io.OutputStream JavaDoc b64os = null;
317         java.io.ObjectOutputStream JavaDoc oos = null;
318         java.util.zip.GZIPOutputStream JavaDoc gzos = null;
319         
320         // Isolate options
321
int gzip = (options & GZIP);
322         int dontBreakLines = (options & DONT_BREAK_LINES);
323         
324         try
325         {
326             // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
327
baos = new java.io.ByteArrayOutputStream JavaDoc();
328             b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
329     
330             // GZip?
331
if( gzip == GZIP )
332             {
333                 gzos = new java.util.zip.GZIPOutputStream JavaDoc( b64os );
334                 oos = new java.io.ObjectOutputStream JavaDoc( gzos );
335             } // end if: gzip
336
else
337                 oos = new java.io.ObjectOutputStream JavaDoc( b64os );
338             
339             oos.writeObject( serializableObject );
340         } // end try
341
catch( java.io.IOException JavaDoc e )
342         {
343             e.printStackTrace();
344             return null;
345         } // end catch
346
finally
347         {
348             try{ oos.close(); } catch( Exception JavaDoc e ){}
349             try{ gzos.close(); } catch( Exception JavaDoc e ){}
350             try{ b64os.close(); } catch( Exception JavaDoc e ){}
351             try{ baos.close(); } catch( Exception JavaDoc e ){}
352         } // end finally
353

354         // Return value according to relevant encoding.
355
try
356         {
357             return new String JavaDoc( baos.toByteArray(), PREFERRED_ENCODING );
358         } // end try
359
catch (java.io.UnsupportedEncodingException JavaDoc uue)
360         {
361             return new String JavaDoc( baos.toByteArray() );
362         } // end catch
363

364     } // end encode
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 JavaDoc encodeBytes( byte[] source )
376     {
377         return encodeBytes( source, 0, source.length, NO_OPTIONS );
378     } // end encodeBytes
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 JavaDoc encodeBytes( byte[] source, int options )
403     {
404         return encodeBytes( source, 0, source.length, options );
405     } // end encodeBytes
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 JavaDoc encodeBytes( byte[] source, int off, int len )
418     {
419         return encodeBytes( source, off, len, NO_OPTIONS );
420     } // end encodeBytes
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 JavaDoc encodeBytes( byte[] source, int off, int len, int options )
447     {
448         // Isolate options
449
int dontBreakLines = ( options & DONT_BREAK_LINES );
450         int gzip = ( options & GZIP );
451         
452         // Compress?
453
if( gzip == GZIP )
454         {
455             java.io.ByteArrayOutputStream JavaDoc baos = null;
456             java.util.zip.GZIPOutputStream JavaDoc gzos = null;
457             Base64.OutputStream b64os = null;
458             
459     
460             try
461             {
462                 // GZip -> Base64 -> ByteArray
463
baos = new java.io.ByteArrayOutputStream JavaDoc();
464                 b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
465                 gzos = new java.util.zip.GZIPOutputStream JavaDoc( b64os );
466             
467                 gzos.write( source, off, len );
468                 gzos.close();
469             } // end try
470
catch( java.io.IOException JavaDoc e )
471             {
472                 e.printStackTrace();
473                 return null;
474             } // end catch
475
finally
476             {
477                 try{ gzos.close(); } catch( Exception JavaDoc e ){}
478                 try{ b64os.close(); } catch( Exception JavaDoc e ){}
479                 try{ baos.close(); } catch( Exception JavaDoc e ){}
480             } // end finally
481

482             // Return value according to relevant encoding.
483
try
484             {
485                 return new String JavaDoc( baos.toByteArray(), PREFERRED_ENCODING );
486             } // end try
487
catch (java.io.UnsupportedEncodingException JavaDoc uue)
488             {
489                 return new String JavaDoc( baos.toByteArray() );
490             } // end catch
491
} // end if: compress
492

493         // Else, don't compress. Better not to use streams at all then.
494
else
495         {
496             // Convert option to boolean in way that code likes it.
497
boolean breakLines = dontBreakLines == 0;
498             
499             int len43 = len * 4 / 3;
500             byte[] outBuff = new byte[ ( len43 ) // Main 4:3
501
+ ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
502
+ (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
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                 } // end if: end of line
518
} // en dfor: each piece of array
519

520             if( d < len )
521             {
522                 encode3to4( source, d+off, len - d, outBuff, e );
523                 e += 4;
524             } // end if: some padding needed
525

526             
527             // Return value according to relevant encoding.
528
try
529             {
530                 return new String JavaDoc( outBuff, 0, e, PREFERRED_ENCODING );
531             } // end try
532
catch (java.io.UnsupportedEncodingException JavaDoc uue)
533             {
534                 return new String JavaDoc( outBuff, 0, e );
535             } // end catch
536

537         } // end else: don't compress
538

539     } // end encodeBytes
540

541
542     
543     
544     
545 /* ******** D E C O D I N G M E T H O D S ******** */
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         // Example: Dk==
573
if( source[ srcOffset + 2] == EQUALS_SIGN )
574         {
575             // Two ways to do the same thing. Don't know which way I like best.
576
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
577
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
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         // Example: DkL=
586
else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
587         {
588             // Two ways to do the same thing. Don't know which way I like best.
589
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
590
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
591
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
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         // Example: DkLE
602
else
603         {
604             try{
605             // Two ways to do the same thing. Don't know which way I like best.
606
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
607
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
608
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
609
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
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 JavaDoc 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             } //e nd catch
628
}
629     } // end decodeToBytes
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 ]; // Upper limit on size of output
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); // Only the low seven bits
659
sbiDecode = DECODABET[ sbiCrop ];
660             
661             if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
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                         // If that was the equals sign, break out of 'for' loop
672
if( sbiCrop == EQUALS_SIGN )
673                             break;
674                     } // end if: quartet built
675

676                 } // end if: equals sign or better
677

678             } // end if: white space, equals sign or better
679
else
680             {
681                 System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
682                 return null;
683             } // end else:
684
} // each input character
685

686         byte[] out = new byte[ outBuffPosn ];
687         System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
688         return out;
689     } // end decode
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 JavaDoc s )
703     {
704         byte[] bytes;
705         try
706         {
707             bytes = s.getBytes( PREFERRED_ENCODING );
708         } // end try
709
catch( java.io.UnsupportedEncodingException JavaDoc uee )
710         {
711             bytes = s.getBytes();
712         } // end catch
713
//</change>
714

715         // Decode
716
bytes = decode( bytes, 0, bytes.length );
717         
718         
719         // Check to see if it's gzip-compressed
720
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
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 JavaDoc bais = null;
728                 java.util.zip.GZIPInputStream JavaDoc gzis = null;
729                 java.io.ByteArrayOutputStream JavaDoc baos = null;
730                 byte[] buffer = new byte[2048];
731                 int length = 0;
732
733                 try
734                 {
735                     baos = new java.io.ByteArrayOutputStream JavaDoc();
736                     bais = new java.io.ByteArrayInputStream JavaDoc( bytes );
737                     gzis = new java.util.zip.GZIPInputStream JavaDoc( bais );
738
739                     while( ( length = gzis.read( buffer ) ) >= 0 )
740                     {
741                         baos.write(buffer,0,length);
742                     } // end while: reading input
743

744                     // No error? Get new bytes.
745
bytes = baos.toByteArray();
746
747                 } // end try
748
catch( java.io.IOException JavaDoc e )
749                 {
750                     // Just return originally-decoded bytes
751
} // end catch
752
finally
753                 {
754                     try{ baos.close(); } catch( Exception JavaDoc e ){}
755                     try{ gzis.close(); } catch( Exception JavaDoc e ){}
756                     try{ bais.close(); } catch( Exception JavaDoc e ){}
757                 } // end finally
758

759             } // end if: gzipped
760
} // end if: bytes.length >= 2
761

762         return bytes;
763     } // end decode
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 JavaDoc decodeToObject( String JavaDoc encodedObject )
777     {
778         // Decode and gunzip if necessary
779
byte[] objBytes = decode( encodedObject );
780         
781     &n