2 package org
.de
.metux
.util
;
5 * Encodes and decodes to and from Base64 notation.
11 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
12 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
13 * where last buffer being read, if not completely full, was not returned.</li>
14 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
15 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
19 * I am placing this code in the Public Domain. Do with it as you will.
20 * This software comes with no guarantees or warranties but with
21 * plenty of well-wishing instead!
22 * Please visit <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a>
23 * periodically to check for updates or to contribute improvements.
26 * @author Robert Harder
27 * @author rob@iharder.net
33 /** Specify encoding (value is <tt>true</tt>). */
34 public final static boolean ENCODE
= true;
37 /** Specify decoding (value is <tt>false</tt>). */
38 public final static boolean DECODE
= false;
41 /** Maximum line length (76) of Base64 output. */
42 private final static int MAX_LINE_LENGTH
= 76;
45 /** The equals sign (=) as a byte. */
46 private final static byte EQUALS_SIGN
= (byte)'=';
49 /** The new line character (\n) as a byte. */
50 private final static byte NEW_LINE
= (byte)'\n';
53 /** The 64 valid Base64 values. */
54 private final static byte[] ALPHABET
=
56 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
57 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
58 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
59 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
60 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
61 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
62 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
63 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
64 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
65 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
69 * Translates a Base64 value to either its 6-bit reconstruction value
70 * or a negative number indicating some other meaning.
72 private final static byte[] DECODABET
=
74 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
75 -5,-5, // Whitespace: Tab and Linefeed
76 -9,-9, // Decimal 11 - 12
77 -5, // Whitespace: Carriage Return
78 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
79 -9,-9,-9,-9,-9, // Decimal 27 - 31
80 -5, // Whitespace: Space
81 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
82 62, // Plus sign at decimal 43
83 -9,-9,-9, // Decimal 44 - 46
84 63, // Slash at decimal 47
85 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
86 -9,-9,-9, // Decimal 58 - 60
87 -1, // Equals sign at decimal 61
88 -9,-9,-9, // Decimal 62 - 64
89 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
90 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
91 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
92 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
93 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
94 -9,-9,-9,-9 // Decimal 123 - 126
95 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
96 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
97 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
98 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
99 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
100 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
101 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
102 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
103 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
104 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
108 // private final static byte BAD_ENCODING = -9; // Indicates error in encoding
109 private final static byte WHITE_SPACE_ENC
= -5; // Indicates white space in encoding
110 private final static byte EQUALS_SIGN_ENC
= -1; // Indicates equals sign in encoding
113 /** Defeats instantiation. */
116 /* ******** E N C O D I N G M E T H O D S ******** */
120 * Encodes the first three bytes of array <var>threeBytes</var>
121 * and returns a four-byte array in Base64 notation.
123 * @param threeBytes the array to convert
124 * @return four byte array in Base64 notation.
127 // private static byte[] encode3to4( byte[] threeBytes )
128 // { return encode3to4( threeBytes, 3 );
129 // } // end encodeToBytes
130 // Is unused and private.
134 * Encodes up to the first three bytes of array <var>threeBytes</var>
135 * and returns a four-byte array in Base64 notation.
136 * The actual number of significant bytes in your array is
137 * given by <var>numSigBytes</var>.
138 * The array <var>threeBytes</var> needs only be as big as
139 * <var>numSigBytes</var>.
141 * @param threeBytes the array to convert
142 * @param numSigBytes the number of significant bytes in your array
143 * @return four byte array in Base64 notation.
146 private static byte[] encode3to4( byte[] threeBytes
, int numSigBytes
)
147 { byte[] dest
= new byte[4];
148 encode3to4( threeBytes
, 0, numSigBytes
, dest
, 0 );
155 * Encodes up to three bytes of the array <var>source</var>
156 * and writes the resulting four Base64 bytes to <var>destination</var>.
157 * The source and destination arrays can be manipulated
158 * anywhere along their length by specifying
159 * <var>srcOffset</var> and <var>destOffset</var>.
160 * This method does not check to make sure your arrays
161 * are large enough to accomodate <var>srcOffset</var> + 3 for
162 * the <var>source</var> array or <var>destOffset</var> + 4 for
163 * the <var>destination</var> array.
164 * The actual number of significant bytes in your array is
165 * given by <var>numSigBytes</var>.
167 * @param source the array to convert
168 * @param srcOffset the index where conversion begins
169 * @param numSigBytes the number of significant bytes in your array
170 * @param destination the array to hold the conversion
171 * @param destOffset the index where output will be put
172 * @return the <var>destination</var> array
175 private static byte[] encode3to4(
176 byte[] source
, int srcOffset
, int numSigBytes
,
177 byte[] destination
, int destOffset
)
180 // 01234567890123456789012345678901 Bit position
181 // --------000000001111111122222222 Array position from threeBytes
182 // --------| || || || | Six bit groups to index ALPHABET
183 // >>18 >>12 >> 6 >> 0 Right shift necessary
184 // 0x3f 0x3f 0x3f Additional AND
186 // Create buffer with zero-padding if there are only one or two
187 // significant bytes passed in the array.
188 // We have to shift left 24 in order to flush out the 1's that appear
189 // when Java treats a value as negative that is cast from a byte to an int.
190 int inBuff
= ( numSigBytes
> 0 ?
((source
[ srcOffset
] << 24) >>> 8) : 0 )
191 | ( numSigBytes
> 1 ?
((source
[ srcOffset
+ 1 ] << 24) >>> 16) : 0 )
192 | ( numSigBytes
> 2 ?
((source
[ srcOffset
+ 2 ] << 24) >>> 24) : 0 );
194 switch( numSigBytes
)
197 destination
[ destOffset
] = ALPHABET
[ (inBuff
>>> 18) ];
198 destination
[ destOffset
+ 1 ] = ALPHABET
[ (inBuff
>>> 12) & 0x3f ];
199 destination
[ destOffset
+ 2 ] = ALPHABET
[ (inBuff
>>> 6) & 0x3f ];
200 destination
[ destOffset
+ 3 ] = ALPHABET
[ (inBuff
) & 0x3f ];
204 destination
[ destOffset
] = ALPHABET
[ (inBuff
>>> 18) ];
205 destination
[ destOffset
+ 1 ] = ALPHABET
[ (inBuff
>>> 12) & 0x3f ];
206 destination
[ destOffset
+ 2 ] = ALPHABET
[ (inBuff
>>> 6) & 0x3f ];
207 destination
[ destOffset
+ 3 ] = EQUALS_SIGN
;
211 destination
[ destOffset
] = ALPHABET
[ (inBuff
>>> 18) ];
212 destination
[ destOffset
+ 1 ] = ALPHABET
[ (inBuff
>>> 12) & 0x3f ];
213 destination
[ destOffset
+ 2 ] = EQUALS_SIGN
;
214 destination
[ destOffset
+ 3 ] = EQUALS_SIGN
;
223 * Serializes an object and returns the Base64-encoded
224 * version of that serialized object. If the object
225 * cannot be serialized or there is another error,
226 * the method will return <tt>null</tt>.
228 * @param serializableObject The object to encode
229 * @return The Base64-encoded object
232 public static String
encodeObject( java
.io
.Serializable serializableObject
)
234 return encodeObject( serializableObject
, true );
235 } // end encodeObject
238 * Serializes an object and returns the Base64-encoded
239 * version of that serialized object. If the object
240 * cannot be serialized or there is another error,
241 * the method will return <tt>null</tt>.
243 * @param serializableObject The object to encode
244 * @param breakLines Break lines at 80 characters or less.
245 * @return The Base64-encoded object
248 public static String
encodeObject( java
.io
.Serializable serializableObject
, boolean breakLines
)
250 java
.io
.ByteArrayOutputStream baos
= null;
251 java
.io
.OutputStream b64os
= null;
252 java
.io
.ObjectOutputStream oos
= null;
256 baos
= new java
.io
.ByteArrayOutputStream();
257 b64os
= new Base64
.OutputStream( baos
, Base64
.ENCODE
, breakLines
);
258 oos
= new java
.io
.ObjectOutputStream( b64os
);
260 oos
.writeObject( serializableObject
);
262 catch( java
.io
.IOException e
)
269 try{ oos
.close(); } catch( Exception e
){}
270 try{ b64os
.close(); } catch( Exception e
){}
271 try{ baos
.close(); } catch( Exception e
){}
274 return new String( baos
.toByteArray() );
279 * Encodes a byte array into Base64 notation.
280 * Equivalen to calling
281 * <code>encodeBytes( source, 0, source.length )</code>
283 * @param source The data to convert
286 public static String
encodeBytes( byte[] source
)
288 return encodeBytes( source
, true );
292 * Encodes a byte array into Base64 notation.
293 * Equivalen to calling
294 * <code>encodeBytes( source, 0, source.length )</code>
296 * @param source The data to convert
297 * @param breakLines Break lines at 80 characters or less.
300 public static String
encodeBytes( byte[] source
, boolean breakLines
)
302 return encodeBytes( source
, 0, source
.length
, breakLines
);
307 * Encodes a byte array into Base64 notation.
309 * @param source The data to convert
310 * @param off Offset in array where conversion should begin
311 * @param len Length of data to convert
314 public static String
encodeBytes( byte[] source
, int off
, int len
)
316 return encodeBytes( source
, off
, len
, true );
321 * Encodes a byte array into Base64 notation.
323 * @param source The data to convert
324 * @param off Offset in array where conversion should begin
325 * @param len Length of data to convert
326 * @param breakLines Break lines at 80 characters or less.
329 public static String
encodeBytes( byte[] source
, int off
, int len
, boolean breakLines
)
331 int len43
= len
* 4 / 3;
332 byte[] outBuff
= new byte[ ( len43
) // Main 4:3
333 + ( (len
% 3) > 0 ?
4 : 0 ) // Account for padding
334 + (breakLines ?
( len43
/ MAX_LINE_LENGTH
) : 0) ]; // New lines
339 for( ; d
< len2
; d
+=3, e
+=4 )
341 encode3to4( source
, d
+off
, 3, outBuff
, e
);
344 if( breakLines
&& lineLength
== MAX_LINE_LENGTH
)
346 outBuff
[e
+4] = NEW_LINE
;
349 } // end if: end of line
350 } // en dfor: each piece of array
354 encode3to4( source
, d
+off
, len
- d
, outBuff
, e
);
356 } // end if: some padding needed
358 return new String( outBuff
, 0, e
);
363 * Encodes a string in Base64 notation with line breaks
364 * after every 75 Base64 characters.
366 * @param s the string to encode
367 * @return the encoded string
370 public static String
encodeString( String s
)
372 return encodeString( s
, true );
373 } // end encodeString
376 * Encodes a string in Base64 notation with line breaks
377 * after every 75 Base64 characters.
379 * @param s the string to encode
380 * @param breakLines Break lines at 80 characters or less.
381 * @return the encoded string
384 public static String
encodeString( String s
, boolean breakLines
)
386 return encodeBytes( s
.getBytes(), breakLines
);
387 } // end encodeString
392 /* ******** D E C O D I N G M E T H O D S ******** */
396 * Decodes the first four bytes of array <var>fourBytes</var>
397 * and returns an array up to three bytes long with the
400 * @param fourBytes the array with Base64 content
401 * @return array with decoded values
404 private static byte[] decode4to3( byte[] fourBytes
)
406 byte[] outBuff1
= new byte[3];
407 int count
= decode4to3( fourBytes
, 0, outBuff1
, 0 );
408 byte[] outBuff2
= new byte[ count
];
410 for( int i
= 0; i
< count
; i
++ )
411 outBuff2
[i
] = outBuff1
[i
];
420 * Decodes four bytes from array <var>source</var>
421 * and writes the resulting bytes (up to three of them)
422 * to <var>destination</var>.
423 * The source and destination arrays can be manipulated
424 * anywhere along their length by specifying
425 * <var>srcOffset</var> and <var>destOffset</var>.
426 * This method does not check to make sure your arrays
427 * are large enough to accomodate <var>srcOffset</var> + 4 for
428 * the <var>source</var> array or <var>destOffset</var> + 3 for
429 * the <var>destination</var> array.
430 * This method returns the actual number of bytes that
431 * were converted from the Base64 encoding.
434 * @param source the array to convert
435 * @param srcOffset the index where conversion begins
436 * @param destination the array to hold the conversion
437 * @param destOffset the index where output will be put
438 * @return the number of decoded bytes converted
441 private static int decode4to3( byte[] source
, int srcOffset
, byte[] destination
, int destOffset
)
444 if( source
[ srcOffset
+ 2] == EQUALS_SIGN
)
446 // Two ways to do the same thing. Don't know which way I like best.
447 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
448 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
449 int outBuff
= ( ( DECODABET
[ source
[ srcOffset
] ] & 0xFF ) << 18 )
450 | ( ( DECODABET
[ source
[ srcOffset
+ 1] ] & 0xFF ) << 12 );
452 destination
[ destOffset
] = (byte)( outBuff
>>> 16 );
457 else if( source
[ srcOffset
+ 3 ] == EQUALS_SIGN
)
459 // Two ways to do the same thing. Don't know which way I like best.
460 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
461 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
462 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
463 int outBuff
= ( ( DECODABET
[ source
[ srcOffset
] ] & 0xFF ) << 18 )
464 | ( ( DECODABET
[ source
[ srcOffset
+ 1 ] ] & 0xFF ) << 12 )
465 | ( ( DECODABET
[ source
[ srcOffset
+ 2 ] ] & 0xFF ) << 6 );
467 destination
[ destOffset
] = (byte)( outBuff
>>> 16 );
468 destination
[ destOffset
+ 1 ] = (byte)( outBuff
>>> 8 );
476 // Two ways to do the same thing. Don't know which way I like best.
477 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
478 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
479 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
480 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
481 int outBuff
= ( ( DECODABET
[ source
[ srcOffset
] ] & 0xFF ) << 18 )
482 | ( ( DECODABET
[ source
[ srcOffset
+ 1 ] ] & 0xFF ) << 12 )
483 | ( ( DECODABET
[ source
[ srcOffset
+ 2 ] ] & 0xFF ) << 6)
484 | ( ( DECODABET
[ source
[ srcOffset
+ 3 ] ] & 0xFF ) );
487 destination
[ destOffset
] = (byte)( outBuff
>> 16 );
488 destination
[ destOffset
+ 1 ] = (byte)( outBuff
>> 8 );
489 destination
[ destOffset
+ 2 ] = (byte)( outBuff
);
492 }catch( Exception e
){
493 System
.out
.println(""+source
[srcOffset
]+ ": " + ( DECODABET
[ source
[ srcOffset
] ] ) );
494 System
.out
.println(""+source
[srcOffset
+1]+ ": " + ( DECODABET
[ source
[ srcOffset
+ 1 ] ] ) );
495 System
.out
.println(""+source
[srcOffset
+2]+ ": " + ( DECODABET
[ source
[ srcOffset
+ 2 ] ] ) );
496 System
.out
.println(""+source
[srcOffset
+3]+ ": " + ( DECODABET
[ source
[ srcOffset
+ 3 ] ] ) );
500 } // end decodeToBytes
505 * Decodes data from Base64 notation.
507 * @param s the string to decode
508 * @return the decoded data
511 public static byte[] decode( String s
)
512 throws DecodeException
514 byte[] bytes
= s
.getBytes();
515 return decode( bytes
, 0, bytes
.length
);
520 * Decodes data from Base64 notation and
521 * returns it as a string.
522 * Equivlaent to calling
523 * <code>new String( decode( s ) )</code>
525 * @param s the strind to decode
526 * @return The data as a string
529 public static String
decodeToString( String s
)
530 throws DecodeException
531 { return new String( decode( s
) );
532 } // end decodeToString
536 * Attempts to decode Base64 data and deserialize a Java
537 * Object within. Returns <tt>null if there was an error.
539 * @param encodedObject The Base64 data to decode
540 * @return The decoded and deserialized object
543 public static Object
decodeToObject( String encodedObject
)
544 throws DecodeException
546 byte[] objBytes
= decode( encodedObject
);
548 java
.io
.ByteArrayInputStream bais
= null;
549 java
.io
.ObjectInputStream ois
= null;
553 bais
= new java
.io
.ByteArrayInputStream( objBytes
);
554 ois
= new java
.io
.ObjectInputStream( bais
);
556 return ois
.readObject();
558 catch( java
.io
.IOException e
)
563 catch( java
.lang
.ClassNotFoundException e
)
570 try{ bais
.close(); } catch( Exception e
){}
571 try{ ois
.close(); } catch( Exception e
){}
573 } // end decodeObject
575 public static class DecodeException
extends Exception
577 DecodeException(String e
)
584 * Decodes Base64 content in byte array format and returns
585 * the decoded byte array.
587 * @param source The Base64 encoded data
588 * @param off The offset of where to begin decoding
589 * @param len The length of characters to decode
590 * @return decoded data
593 public static byte[] decode( byte[] source
, int off
, int len
)
594 throws DecodeException
596 int len34
= len
* 3 / 4;
597 byte[] outBuff
= new byte[ len34
]; // Upper limit on size of output
600 byte[] b4
= new byte[4];
605 for( i
= 0; i
< len
; i
++ )
607 sbiCrop
= (byte)(source
[i
] & 0x7f); // Only the low seven bits
608 sbiDecode
= DECODABET
[ sbiCrop
];
610 if( sbiDecode
>= WHITE_SPACE_ENC
) // White space, Equals sign or better
612 if( sbiDecode
>= EQUALS_SIGN_ENC
)
614 b4
[ b4Posn
++ ] = sbiCrop
;
617 outBuffPosn
+= decode4to3( b4
, 0, outBuff
, outBuffPosn
);
620 // If that was the equals sign, break out of 'for' loop
621 if( sbiCrop
== EQUALS_SIGN
)
623 } // end if: quartet built
625 } // end if: equals sign or better
627 } // end if: white space, equals sign or better
629 throw new DecodeException("Bad Base64 input character at " + i
+ ": " + source
[i
] + "(decimal)" );
630 } // each input character
632 byte[] out
= new byte[ outBuffPosn
];
633 System
.arraycopy( outBuff
, 0, out
, 0, outBuffPosn
);
640 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
645 * A {@link Base64#InputStream} will read data from another
646 * {@link java.io.InputStream}, given in the constructor,
647 * and encode/decode to/from Base64 notation on the fly.
650 * @see java.io.FilterInputStream
653 public static class InputStream
extends java
.io
.FilterInputStream
655 private boolean encode
; // Encoding or decoding
656 private int position
; // Current position in the buffer
657 private byte[] buffer
; // Small buffer holding converted data
658 private int bufferLength
; // Length of buffer (3 or 4)
659 private int numSigBytes
; // Number of meaningful bytes in the buffer
660 private int lineLength
;
661 private boolean breakLines
; // Break lines at less than 80 characters
665 * Constructs a {@link Base64#InputStream} in DECODE mode.
667 * @param in the {@link java.io.InputStream} from which to read data.
670 public InputStream( java
.io
.InputStream in
)
672 this( in
, Base64
.DECODE
);
677 * Constructs a {@link Base64#InputStream} in
678 * either ENCODE or DECODE mode.
680 * @param in the {@link java.io.InputStream} from which to read data.
681 * @param encode Conversion direction
686 public InputStream( java
.io
.InputStream in
, boolean encode
)
688 this( in
, encode
, true );
693 * Constructs a {@link Base64#InputStream} in
694 * either ENCODE or DECODE mode.
696 * @param in the {@link java.io.InputStream} from which to read data.
697 * @param encode Conversion direction
698 * @param breakLines Break lines at less than 80 characters.
703 public InputStream( java
.io
.InputStream in
, boolean encode
, boolean breakLines
)
706 this.breakLines
= breakLines
;
707 this.encode
= encode
;
708 this.bufferLength
= encode ?
4 : 3;
709 this.buffer
= new byte[ bufferLength
];
715 * Reads enough of the input stream to convert
716 * to/from Base64 and returns the next byte.
721 public int read() throws java
.io
.IOException
723 // Do we need to get data?
728 byte[] b3
= new byte[3];
729 int numBinaryBytes
= 0;
730 for( int i
= 0; i
< 3; i
++ )
736 // If end of stream, b is -1.
741 } // end if: not end of stream
744 catch( java
.io
.IOException e
)
746 // Only a problem if we got no data at all.
751 } // end for: each needed input byte
753 if( numBinaryBytes
> 0 )
755 encode3to4( b3
, 0, numBinaryBytes
, buffer
, 0 );
758 } // end if: got data
763 } // end if: encoding
768 byte[] b4
= new byte[4];
770 for( i
= 0; i
< 4; i
++ )
772 // Read four "meaningful" bytes:
775 while( b
>= 0 && DECODABET
[ b
& 0x7f ] <= WHITE_SPACE_ENC
);
778 break; // Reads a -1 if end of stream
781 } // end for: each needed input byte
785 numSigBytes
= decode4to3( b4
, 0, buffer
, 0 );
787 } // end if: got four characters
790 } // end else if: also padded correctly
793 // Must have broken out from above.
794 throw new java
.io
.IOException( "Improperly padded Base64 input." );
797 } // end else: decode
798 } // end else: get data
803 // End of relevant data?
804 if( /*!encode &&*/ position
>= numSigBytes
)
807 if( encode
&& breakLines
&& lineLength
>= MAX_LINE_LENGTH
)
814 lineLength
++; // This isn't important when decoding
815 // but throwing an extra "if" seems
818 int b
= buffer
[ position
++ ];
820 if( position
>= bufferLength
)
823 return b
& 0xFF; // This is how you "cast" a byte that's
824 // intended to be unsigned.
826 } // end if: position >= 0
831 // When JDK1.4 is more accepted, use an assertion here.
832 throw new java
.io
.IOException( "Error in Base64 code reading stream." );
838 * Calls {@link #read} repeatedly until the end of stream
839 * is reached or <var>len</var> bytes are read.
840 * Returns number of bytes read into array or -1 if
841 * end of stream is encountered.
843 * @param dest array to hold values
844 * @param off offset for array
845 * @param len max number of bytes to read into array
846 * @return bytes read into array or -1 if end of stream is encountered.
849 public int read( byte[] dest
, int off
, int len
) throws java
.io
.IOException
853 for( i
= 0; i
< len
; i
++ )
857 //if( b < 0 && i == 0 )
861 dest
[off
+ i
] = (byte)b
;
865 break; // Out of 'for' loop
866 } // end for: each byte read
870 } // end inner class InputStream
877 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
882 * A {@link Base64#OutputStream} will write data to another
883 * {@link java.io.OutputStream}, given in the constructor,
884 * and encode/decode to/from Base64 notation on the fly.
887 * @see java.io.FilterOutputStream
890 public static class OutputStream
extends java
.io
.FilterOutputStream
892 private boolean encode
;
893 private int position
;
894 private byte[] buffer
;
895 private int bufferLength
;
896 private int lineLength
;
897 private boolean breakLines
;
901 * Constructs a {@link Base64#OutputStream} in ENCODE mode.
903 * @param out the {@link java.io.OutputStream} to which data will be written.
906 public OutputStream( java
.io
.OutputStream out
)
908 this( out
, Base64
.ENCODE
);
913 * Constructs a {@link Base64#OutputStream} in
914 * either ENCODE or DECODE mode.
916 * @param out the {@link java.io.OutputStream} to which data will be written.
917 * @param encode Conversion direction
922 public OutputStream( java
.io
.OutputStream out
, boolean encode
)
924 this( out
, encode
, true );
929 * Constructs a {@link Base64#OutputStream} in
930 * either ENCODE or DECODE mode.
932 * @param out the {@link java.io.OutputStream} to which data will be written.
933 * @param encode Conversion direction
934 * @param breakLines Break lines to be less than 80 characters.
939 public OutputStream( java
.io
.OutputStream out
, boolean encode
, boolean breakLines
)
942 this.breakLines
= breakLines
;
943 this.encode
= encode
;
944 this.bufferLength
= encode ?
3 : 4;
945 this.buffer
= new byte[ bufferLength
];
952 * Writes the byte to the output stream after
953 * converting to/from Base64 notation.
954 * When encoding, bytes are buffered three
955 * at a time before the output stream actually
956 * gets a write() call.
957 * When decoding, bytes are buffered four
960 * @param theByte the byte to write
963 public void write(int theByte
) throws java
.io
.IOException
967 buffer
[ position
++ ] = (byte)theByte
;
968 if( position
>= bufferLength
) // Enough to encode.
970 out
.write( Base64
.encode3to4( buffer
, bufferLength
) );
973 if( breakLines
&& lineLength
>= MAX_LINE_LENGTH
)
975 out
.write( NEW_LINE
);
977 } // end if: end of line
980 } // end if: enough to output
981 } // end if: encoding
986 // Meaningful Base64 character?
987 if( DECODABET
[ theByte
& 0x7f ] > WHITE_SPACE_ENC
)
989 buffer
[ position
++ ] = (byte)theByte
;
990 if( position
>= bufferLength
) // Enough to output.
992 out
.write( Base64
.decode4to3( buffer
) );
994 } // end if: enough to output
995 } // end if: meaningful base64 character
996 else if( DECODABET
[ theByte
& 0x7f ] != WHITE_SPACE_ENC
)
998 throw new java
.io
.IOException( "Invalid character in Base64 data." );
999 } // end else: not white space either
1000 } // end else: decoding
1006 * Calls {@link #write} repeatedly until <var>len</var>
1007 * bytes are written.
1009 * @param theBytes array from which to read bytes
1010 * @param off offset for array
1011 * @param len max number of bytes to read into array
1014 public void write( byte[] theBytes
, int off
, int len
) throws java
.io
.IOException
1016 for( int i
= 0; i
< len
; i
++ )
1018 write( theBytes
[ off
+ i
] );
1019 } // end for: each byte written
1025 * Appropriately pads Base64 notation when encoding
1026 * or throws an exception if Base64 input is not
1027 * properly padded when decoding.
1031 public void flush() throws java
.io
.IOException
1039 out
.write( Base64
.encode3to4( buffer
, position
) );
1041 } // end if: encoding
1044 throw new java
.io
.IOException( "Base64 input not properly padded." );
1045 } // end else: decoding
1046 } // end if: buffer partially full
1053 * Flushes and closes (I think, in the superclass) the stream.
1057 public void close() throws java
.io
.IOException
1068 } // end inner class OutputStream
1071 } // end class Base64