Update ooo320-m1
[ooovba.git] / filter / source / xsltfilter / Base64.java
blobbd39696f4357229a6ee948a879ac0e43b6ad8795
1 /************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: Base64.java,v $
10 * $Revision: 1.2 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
30 /**
31 * <p>Encodes and decodes to and from Base64 notation.</p>
32 * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
34 * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
35 * several pieces of information to the encoder. In the "higher level" methods such as
36 * encodeBytes( bytes, options ) the options parameter can be used to indicate such
37 * things as first gzipping the bytes before encoding them, not inserting linefeeds
38 * (though that breaks strict Base64 compatibility), and encoding using the URL-safe
39 * and Ordered dialects.</p>
41 * <p>The constants defined in Base64 can be OR-ed together to combine options, so you
42 * might make a call like this:</p>
44 * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DONT_BREAK_LINES );</code>
46 * <p>to compress the data before encoding it and then making the output have no newline characters.</p>
49 * <p>
50 * Change Log:
51 * </p>
52 * <ul>
53 * <li>v2.2.2 - Fixed encodeFileToFile and decodeFileToFile to use the
54 * Base64.InputStream class to encode and decode on the fly which uses
55 * less memory than encoding/decoding an entire file into memory before writing.</li>
56 * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
57 * when using very small files (~< 40 bytes).</li>
58 * <li>v2.2 - Added some helper methods for encoding/decoding directly from
59 * one file to the next. Also added a main() method to support command line
60 * encoding/decoding from one file to the next. Also added these Base64 dialects:
61 * <ol>
62 * <li>The default is RFC3548 format.</li>
63 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
64 * URL and file name friendly format as described in Section 4 of RFC3548.
65 * http://www.faqs.org/rfcs/rfc3548.html</li>
66 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
67 * URL and file name friendly format that preserves lexical ordering as described
68 * in http://www.faqs.org/qa/rfcc-1940.html</li>
69 * </ol>
70 * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
71 * for contributing the new Base64 dialects.
72 * </li>
74 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
75 * some convenience methods for reading and writing to and from files.</li>
76 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
77 * with other encodings (like EBCDIC).</li>
78 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
79 * encoded data was a single byte.</li>
80 * <li>v2.0 - I got rid of methods that used booleans to set options.
81 * Now everything is more consolidated and cleaner. The code now detects
82 * when data that's being decoded is gzip-compressed and will decompress it
83 * automatically. Generally things are cleaner. You'll probably have to
84 * change some method calls that you were making to support the new
85 * options format (<tt>int</tt>s that you "OR" together).</li>
86 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
87 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
88 * Added the ability to "suspend" encoding in the Output Stream so
89 * you can turn on and off the encoding if you need to embed base64
90 * data in an otherwise "normal" stream (like an XML file).</li>
91 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
92 * This helps when using GZIP streams.
93 * Added the ability to GZip-compress objects before encoding them.</li>
94 * <li>v1.4 - Added helper methods to read/write files.</li>
95 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
96 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
97 * where last buffer being read, if not completely full, was not returned.</li>
98 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
99 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
100 * </ul>
102 * <p>
103 * I am placing this code in the Public Domain. Do with it as you will.
104 * This software comes with no guarantees or warranties but with
105 * plenty of well-wishing instead!
106 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
107 * periodically to check for updates or to contribute improvements.
108 * </p>
110 * @author Robert Harder
111 * @author rob@iharder.net
112 * @version 2.2.2
114 public class Base64
117 /* ******** P U B L I C F I E L D S ******** */
120 /** No options specified. Value is zero. */
121 public final static int NO_OPTIONS = 0;
123 /** Specify encoding. */
124 public final static int ENCODE = 1;
127 /** Specify decoding. */
128 public final static int DECODE = 0;
131 /** Specify that data should be gzip-compressed. */
132 public final static int GZIP = 2;
135 /** Don't break lines when encoding (violates strict Base64 specification) */
136 public final static int DONT_BREAK_LINES = 8;
138 /**
139 * Encode using Base64-like encoding that is URL- and Filename-safe as described
140 * in Section 4 of RFC3548:
141 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
142 * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
143 * or at the very least should not be called Base64 without also specifying that is
144 * was encoded using the URL- and Filename-safe dialect.
146 public final static int URL_SAFE = 16;
150 * Encode using the special "ordered" dialect of Base64 described here:
151 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
153 public final static int ORDERED = 32;
156 /* ******** P R I V A T E F I E L D S ******** */
159 /** Maximum line length (76) of Base64 output. */
160 private final static int MAX_LINE_LENGTH = 76;
163 /** The equals sign (=) as a byte. */
164 private final static byte EQUALS_SIGN = (byte)'=';
167 /** The new line character (\n) as a byte. */
168 private final static byte NEW_LINE = (byte)'\n';
171 /** Preferred encoding. */
172 private final static String PREFERRED_ENCODING = "UTF-8";
175 // I think I end up not using the BAD_ENCODING indicator.
176 //private final static byte BAD_ENCODING = -9; // Indicates error in encoding
177 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
178 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
181 /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
183 /** The 64 valid Base64 values. */
184 //private final static byte[] ALPHABET;
185 /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
186 private final static byte[] _STANDARD_ALPHABET =
188 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
189 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
190 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
191 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
192 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
193 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
194 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
195 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
196 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
197 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
201 /**
202 * Translates a Base64 value to either its 6-bit reconstruction value
203 * or a negative number indicating some other meaning.
205 private final static byte[] _STANDARD_DECODABET =
207 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
208 -5,-5, // Whitespace: Tab and Linefeed
209 -9,-9, // Decimal 11 - 12
210 -5, // Whitespace: Carriage Return
211 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
212 -9,-9,-9,-9,-9, // Decimal 27 - 31
213 -5, // Whitespace: Space
214 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
215 62, // Plus sign at decimal 43
216 -9,-9,-9, // Decimal 44 - 46
217 63, // Slash at decimal 47
218 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
219 -9,-9,-9, // Decimal 58 - 60
220 -1, // Equals sign at decimal 61
221 -9,-9,-9, // Decimal 62 - 64
222 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
223 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
224 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
225 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
226 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
227 -9,-9,-9,-9 // Decimal 123 - 126
228 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
229 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
231 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
232 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
233 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
234 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
235 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
236 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
237 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
241 /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
244 * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
245 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
246 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
248 private final static byte[] _URL_SAFE_ALPHABET =
250 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
251 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
252 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
253 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
254 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
255 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
256 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
257 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
258 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
259 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
263 * Used in decoding URL- and Filename-safe dialects of Base64.
265 private final static byte[] _URL_SAFE_DECODABET =
267 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
268 -5,-5, // Whitespace: Tab and Linefeed
269 -9,-9, // Decimal 11 - 12
270 -5, // Whitespace: Carriage Return
271 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
272 -9,-9,-9,-9,-9, // Decimal 27 - 31
273 -5, // Whitespace: Space
274 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
275 -9, // Plus sign at decimal 43
276 -9, // Decimal 44
277 62, // Minus sign at decimal 45
278 -9, // Decimal 46
279 -9, // Slash at decimal 47
280 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
281 -9,-9,-9, // Decimal 58 - 60
282 -1, // Equals sign at decimal 61
283 -9,-9,-9, // Decimal 62 - 64
284 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
285 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
286 -9,-9,-9,-9, // Decimal 91 - 94
287 63, // Underscore at decimal 95
288 -9, // Decimal 96
289 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
290 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
291 -9,-9,-9,-9 // Decimal 123 - 126
292 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
293 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
294 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
295 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
296 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
297 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
298 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
299 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
300 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
301 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
306 /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
309 * I don't get the point of this technique, but it is described here:
310 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
312 private final static byte[] _ORDERED_ALPHABET =
314 (byte)'-',
315 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
316 (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
317 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
318 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
319 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
320 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
321 (byte)'_',
322 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
323 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
324 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
325 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
329 * Used in decoding the "ordered" dialect of Base64.
331 private final static byte[] _ORDERED_DECODABET =
333 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
334 -5,-5, // Whitespace: Tab and Linefeed
335 -9,-9, // Decimal 11 - 12
336 -5, // Whitespace: Carriage Return
337 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
338 -9,-9,-9,-9,-9, // Decimal 27 - 31
339 -5, // Whitespace: Space
340 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
341 -9, // Plus sign at decimal 43
342 -9, // Decimal 44
343 0, // Minus sign at decimal 45
344 -9, // Decimal 46
345 -9, // Slash at decimal 47
346 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
347 -9,-9,-9, // Decimal 58 - 60
348 -1, // Equals sign at decimal 61
349 -9,-9,-9, // Decimal 62 - 64
350 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
351 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
352 -9,-9,-9,-9, // Decimal 91 - 94
353 37, // Underscore at decimal 95
354 -9, // Decimal 96
355 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
356 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
357 -9,-9,-9,-9 // Decimal 123 - 126
358 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
359 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
360 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
361 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
362 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
363 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
364 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
365 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
366 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
367 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
371 /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
375 * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
376 * the options specified.
377 * It's possible, though silly, to specify ORDERED and URLSAFE
378 * in which case one of them will be picked, though there is
379 * no guarantee as to which one will be picked.
381 private final static byte[] getAlphabet( int options )
383 if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET;
384 else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET;
385 else return _STANDARD_ALPHABET;
387 } // end getAlphabet
391 * Returns one of the _SOMETHING_DECODABET byte arrays depending on
392 * the options specified.
393 * It's possible, though silly, to specify ORDERED and URL_SAFE
394 * in which case one of them will be picked, though there is
395 * no guarantee as to which one will be picked.
397 private final static byte[] getDecodabet( int options )
399 if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET;
400 else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET;
401 else return _STANDARD_DECODABET;
403 } // end getAlphabet
407 /** Defeats instantiation. */
408 private Base64(){}
412 * Encodes or decodes two files from the command line;
413 * <strong>feel free to delete this method (in fact you probably should)
414 * if you're embedding this code into a larger program.</strong>
416 public final static void main( String[] args )
418 if( args.length < 3 ){
419 usage("Not enough arguments.");
420 } // end if: args.length < 3
421 else {
422 String flag = args[0];
423 String infile = args[1];
424 String outfile = args[2];
425 if( flag.equals( "-e" ) ){
426 Base64.encodeFileToFile( infile, outfile );
427 } // end if: encode
428 else if( flag.equals( "-d" ) ) {
429 Base64.decodeFileToFile( infile, outfile );
430 } // end else if: decode
431 else {
432 usage( "Unknown flag: " + flag );
433 } // end else
434 } // end else
435 } // end main
438 * Prints command line usage.
440 * @param msg A message to include with usage info.
442 private final static void usage( String msg )
444 System.err.println( msg );
445 System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" );
446 } // end usage
449 /* ******** E N C O D I N G M E T H O D S ******** */
453 * Encodes up to the first three bytes of array <var>threeBytes</var>
454 * and returns a four-byte array in Base64 notation.
455 * The actual number of significant bytes in your array is
456 * given by <var>numSigBytes</var>.
457 * The array <var>threeBytes</var> needs only be as big as
458 * <var>numSigBytes</var>.
459 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
461 * @param b4 A reusable byte array to reduce array instantiation
462 * @param threeBytes the array to convert
463 * @param numSigBytes the number of significant bytes in your array
464 * @return four byte array in Base64 notation.
465 * @since 1.5.1
467 private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options )
469 encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
470 return b4;
471 } // end encode3to4
475 * <p>Encodes up to three bytes of the array <var>source</var>
476 * and writes the resulting four Base64 bytes to <var>destination</var>.
477 * The source and destination arrays can be manipulated
478 * anywhere along their length by specifying
479 * <var>srcOffset</var> and <var>destOffset</var>.
480 * This method does not check to make sure your arrays
481 * are large enough to accomodate <var>srcOffset</var> + 3 for
482 * the <var>source</var> array or <var>destOffset</var> + 4 for
483 * the <var>destination</var> array.
484 * The actual number of significant bytes in your array is
485 * given by <var>numSigBytes</var>.</p>
486 * <p>This is the lowest level of the encoding methods with
487 * all possible parameters.</p>
489 * @param source the array to convert
490 * @param srcOffset the index where conversion begins
491 * @param numSigBytes the number of significant bytes in your array
492 * @param destination the array to hold the conversion
493 * @param destOffset the index where output will be put
494 * @return the <var>destination</var> array
495 * @since 1.3
497 private static byte[] encode3to4(
498 byte[] source, int srcOffset, int numSigBytes,
499 byte[] destination, int destOffset, int options )
501 byte[] ALPHABET = getAlphabet( options );
503 // 1 2 3
504 // 01234567890123456789012345678901 Bit position
505 // --------000000001111111122222222 Array position from threeBytes
506 // --------| || || || | Six bit groups to index ALPHABET
507 // >>18 >>12 >> 6 >> 0 Right shift necessary
508 // 0x3f 0x3f 0x3f Additional AND
510 // Create buffer with zero-padding if there are only one or two
511 // significant bytes passed in the array.
512 // We have to shift left 24 in order to flush out the 1's that appear
513 // when Java treats a value as negative that is cast from a byte to an int.
514 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
515 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
516 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
518 switch( numSigBytes )
520 case 3:
521 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
522 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
523 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
524 destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
525 return destination;
527 case 2:
528 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
529 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
530 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
531 destination[ destOffset + 3 ] = EQUALS_SIGN;
532 return destination;
534 case 1:
535 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
536 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
537 destination[ destOffset + 2 ] = EQUALS_SIGN;
538 destination[ destOffset + 3 ] = EQUALS_SIGN;
539 return destination;
541 default:
542 return destination;
543 } // end switch
544 } // end encode3to4
549 * Serializes an object and returns the Base64-encoded
550 * version of that serialized object. If the object
551 * cannot be serialized or there is another error,
552 * the method will return <tt>null</tt>.
553 * The object is not GZip-compressed before being encoded.
555 * @param serializableObject The object to encode
556 * @return The Base64-encoded object
557 * @since 1.4
559 public static String encodeObject( java.io.Serializable serializableObject )
561 return encodeObject( serializableObject, NO_OPTIONS );
562 } // end encodeObject
567 * Serializes an object and returns the Base64-encoded
568 * version of that serialized object. If the object
569 * cannot be serialized or there is another error,
570 * the method will return <tt>null</tt>.
571 * <p>
572 * Valid options:<pre>
573 * GZIP: gzip-compresses object before encoding it.
574 * DONT_BREAK_LINES: don't break lines at 76 characters
575 * <i>Note: Technically, this makes your encoding non-compliant.</i>
576 * </pre>
577 * <p>
578 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
579 * <p>
580 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
582 * @param serializableObject The object to encode
583 * @param options Specified options
584 * @return The Base64-encoded object
585 * @see Base64#GZIP
586 * @see Base64#DONT_BREAK_LINES
587 * @since 2.0
589 public static String encodeObject( java.io.Serializable serializableObject, int options )
591 // Streams
592 java.io.ByteArrayOutputStream baos = null;
593 java.io.OutputStream b64os = null;
594 java.io.ObjectOutputStream oos = null;
595 java.util.zip.GZIPOutputStream gzos = null;
597 // Isolate options
598 int gzip = (options & GZIP);
599 int dontBreakLines = (options & DONT_BREAK_LINES);
603 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
604 baos = new java.io.ByteArrayOutputStream();
605 b64os = new Base64.OutputStream( baos, ENCODE | options );
607 // GZip?
608 if( gzip == GZIP )
610 gzos = new java.util.zip.GZIPOutputStream( b64os );
611 oos = new java.io.ObjectOutputStream( gzos );
612 } // end if: gzip
613 else
614 oos = new java.io.ObjectOutputStream( b64os );
616 oos.writeObject( serializableObject );
617 } // end try
618 catch( java.io.IOException e )
620 e.printStackTrace();
621 return null;
622 } // end catch
623 finally
625 try{ oos.close(); } catch( Exception e ){}
626 try{ gzos.close(); } catch( Exception e ){}
627 try{ b64os.close(); } catch( Exception e ){}
628 try{ baos.close(); } catch( Exception e ){}
629 } // end finally
631 // Return value according to relevant encoding.
632 try
634 return new String( baos.toByteArray(), PREFERRED_ENCODING );
635 } // end try
636 catch (java.io.UnsupportedEncodingException uue)
638 return new String( baos.toByteArray() );
639 } // end catch
641 } // end encode
646 * Encodes a byte array into Base64 notation.
647 * Does not GZip-compress data.
649 * @param source The data to convert
650 * @since 1.4
652 public static String encodeBytes( byte[] source )
654 return encodeBytes( source, 0, source.length, NO_OPTIONS );
655 } // end encodeBytes
660 * Encodes a byte array into Base64 notation.
661 * <p>
662 * Valid options:<pre>
663 * GZIP: gzip-compresses object before encoding it.
664 * DONT_BREAK_LINES: don't break lines at 76 characters
665 * <i>Note: Technically, this makes your encoding non-compliant.</i>
666 * </pre>
667 * <p>
668 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
669 * <p>
670 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
673 * @param source The data to convert
674 * @param options Specified options
675 * @see Base64#GZIP
676 * @see Base64#DONT_BREAK_LINES
677 * @since 2.0
679 public static String encodeBytes( byte[] source, int options )
681 return encodeBytes( source, 0, source.length, options );
682 } // end encodeBytes
686 * Encodes a byte array into Base64 notation.
687 * Does not GZip-compress data.
689 * @param source The data to convert
690 * @param off Offset in array where conversion should begin
691 * @param len Length of data to convert
692 * @since 1.4
694 public static String encodeBytes( byte[] source, int off, int len )
696 return encodeBytes( source, off, len, NO_OPTIONS );
697 } // end encodeBytes
702 * Encodes a byte array into Base64 notation.
703 * <p>
704 * Valid options:<pre>
705 * GZIP: gzip-compresses object before encoding it.
706 * DONT_BREAK_LINES: don't break lines at 76 characters
707 * <i>Note: Technically, this makes your encoding non-compliant.</i>
708 * </pre>
709 * <p>
710 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
711 * <p>
712 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
715 * @param source The data to convert
716 * @param off Offset in array where conversion should begin
717 * @param len Length of data to convert
718 * @param options Specified options
719 * @param options alphabet type is pulled from this (standard, url-safe, ordered)
720 * @see Base64#GZIP
721 * @see Base64#DONT_BREAK_LINES
722 * @since 2.0
724 public static String encodeBytes( byte[] source, int off, int len, int options )
726 // Isolate options
727 int dontBreakLines = ( options & DONT_BREAK_LINES );
728 int gzip = ( options & GZIP );
730 // Compress?
731 if( gzip == GZIP )
733 java.io.ByteArrayOutputStream baos = null;
734 java.util.zip.GZIPOutputStream gzos = null;
735 Base64.OutputStream b64os = null;
740 // GZip -> Base64 -> ByteArray
741 baos = new java.io.ByteArrayOutputStream();
742 b64os = new Base64.OutputStream( baos, ENCODE | options );
743 gzos = new java.util.zip.GZIPOutputStream( b64os );
745 gzos.write( source, off, len );
746 gzos.close();
747 } // end try
748 catch( java.io.IOException e )
750 e.printStackTrace();
751 return null;
752 } // end catch
753 finally
755 try{ gzos.close(); } catch( Exception e ){}
756 try{ b64os.close(); } catch( Exception e ){}
757 try{ baos.close(); } catch( Exception e ){}
758 } // end finally
760 // Return value according to relevant encoding.
763 return new String( baos.toByteArray(), PREFERRED_ENCODING );
764 } // end try
765 catch (java.io.UnsupportedEncodingException uue)
767 return new String( baos.toByteArray() );
768 } // end catch
769 } // end if: compress
771 // Else, don't compress. Better not to use streams at all then.
772 else
774 // Convert option to boolean in way that code likes it.
775 boolean breakLines = dontBreakLines == 0;
777 int len43 = len * 4 / 3;
778 byte[] outBuff = new byte[ ( len43 ) // Main 4:3
779 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
780 + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
781 int d = 0;
782 int e = 0;
783 int len2 = len - 2;
784 int lineLength = 0;
785 for( ; d < len2; d+=3, e+=4 )
787 encode3to4( source, d+off, 3, outBuff, e, options );
789 lineLength += 4;
790 if( breakLines && lineLength == MAX_LINE_LENGTH )
792 outBuff[e+4] = NEW_LINE;
793 e++;
794 lineLength = 0;
795 } // end if: end of line
796 } // en dfor: each piece of array
798 if( d < len )
800 encode3to4( source, d+off, len - d, outBuff, e, options );
801 e += 4;
802 } // end if: some padding needed
805 // Return value according to relevant encoding.
808 return new String( outBuff, 0, e, PREFERRED_ENCODING );
809 } // end try
810 catch (java.io.UnsupportedEncodingException uue)
812 return new String( outBuff, 0, e );
813 } // end catch
815 } // end else: don't compress
817 } // end encodeBytes
823 /* ******** D E C O D I N G M E T H O D S ******** */
827 * Decodes four bytes from array <var>source</var>
828 * and writes the resulting bytes (up to three of them)
829 * to <var>destination</var>.
830 * The source and destination arrays can be manipulated
831 * anywhere along their length by specifying
832 * <var>srcOffset</var> and <var>destOffset</var>.
833 * This method does not check to make sure your arrays
834 * are large enough to accomodate <var>srcOffset</var> + 4 for
835 * the <var>source</var> array or <var>destOffset</var> + 3 for
836 * the <var>destination</var> array.
837 * This method returns the actual number of bytes that
838 * were converted from the Base64 encoding.
839 * <p>This is the lowest level of the decoding methods with
840 * all possible parameters.</p>
843 * @param source the array to convert
844 * @param srcOffset the index where conversion begins
845 * @param destination the array to hold the conversion
846 * @param destOffset the index where output will be put
847 * @param options alphabet type is pulled from this (standard, url-safe, ordered)
848 * @return the number of decoded bytes converted
849 * @since 1.3
851 private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options )
853 byte[] DECODABET = getDecodabet( options );
855 // Example: Dk==
856 if( source[ srcOffset + 2] == EQUALS_SIGN )
858 // Two ways to do the same thing. Don't know which way I like best.
859 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
860 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
861 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
862 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
864 destination[ destOffset ] = (byte)( outBuff >>> 16 );
865 return 1;
868 // Example: DkL=
869 else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
871 // Two ways to do the same thing. Don't know which way I like best.
872 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
873 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
874 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
875 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
876 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
877 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
879 destination[ destOffset ] = (byte)( outBuff >>> 16 );
880 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
881 return 2;
884 // Example: DkLE
885 else
887 try{
888 // Two ways to do the same thing. Don't know which way I like best.
889 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
890 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
891 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
892 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
893 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
894 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
895 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
896 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
899 destination[ destOffset ] = (byte)( outBuff >> 16 );
900 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
901 destination[ destOffset + 2 ] = (byte)( outBuff );
903 return 3;
904 }catch( Exception e){
905 System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
906 System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
907 System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
908 System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
909 return -1;
910 } // end catch
912 } // end decodeToBytes
918 * Very low-level access to decoding ASCII characters in
919 * the form of a byte array. Does not support automatically
920 * gunzipping or any other "fancy" features.
922 * @param source The Base64 encoded data
923 * @param off The offset of where to begin decoding
924 * @param len The length of characters to decode
925 * @return decoded data
926 * @since 1.3
928 public static byte[] decode( byte[] source, int off, int len, int options )
930 byte[] DECODABET = getDecodabet( options );
932 int len34 = len * 3 / 4;
933 byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
934 int outBuffPosn = 0;
936 byte[] b4 = new byte[4];
937 int b4Posn = 0;
938 int i = 0;
939 byte sbiCrop = 0;
940 byte sbiDecode = 0;
941 for( i = off; i < off+len; i++ )
943 sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
944 sbiDecode = DECODABET[ sbiCrop ];
946 if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
948 if( sbiDecode >= EQUALS_SIGN_ENC )
950 b4[ b4Posn++ ] = sbiCrop;
951 if( b4Posn > 3 )
953 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
954 b4Posn = 0;
956 // If that was the equals sign, break out of 'for' loop
957 if( sbiCrop == EQUALS_SIGN )
958 break;
959 } // end if: quartet built
961 } // end if: equals sign or better
963 } // end if: white space, equals sign or better
964 else
966 System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
967 return null;
968 } // end else:
969 } // each input character
971 byte[] out = new byte[ outBuffPosn ];
972 System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
973 return out;
974 } // end decode
980 * Decodes data from Base64 notation, automatically
981 * detecting gzip-compressed data and decompressing it.
983 * @param s the string to decode
984 * @return the decoded data
985 * @since 1.4
987 public static byte[] decode( String s )
989 return decode( s, NO_OPTIONS );
994 * Decodes data from Base64 notation, automatically
995 * detecting gzip-compressed data and decompressing it.
997 * @param s the string to decode
998 * @param options encode options such as URL_SAFE
999 * @return the decoded data
1000 * @since 1.4
1002 public static byte[] decode( String s, int options )
1004 byte[] bytes;
1007 bytes = s.getBytes( PREFERRED_ENCODING );
1008 } // end try
1009 catch( java.io.UnsupportedEncodingException uee )
1011 bytes = s.getBytes();
1012 } // end catch
1013 //</change>
1015 // Decode
1016 bytes = decode( bytes, 0, bytes.length, options );
1019 // Check to see if it's gzip-compressed
1020 // GZIP Magic Two-Byte Number: 0x8b1f (35615)
1021 if( bytes != null && bytes.length >= 4 )
1024 int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
1025 if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
1027 java.io.ByteArrayInputStream bais = null;
1028 java.util.zip.GZIPInputStream gzis = null;
1029 java.io.ByteArrayOutputStream baos = null;
1030 byte[] buffer = new byte[2048];
1031 int length = 0;
1035 baos = new java.io.ByteArrayOutputStream();
1036 bais = new java.io.ByteArrayInputStream( bytes );
1037 gzis = new java.util.zip.GZIPInputStream( bais );
1039 while( ( length = gzis.read( buffer ) ) >= 0 )
1041 baos.write(buffer,0,length);
1042 } // end while: reading input
1044 // No error? Get new bytes.
1045 bytes = baos.toByteArray();
1047 } // end try
1048 catch( java.io.IOException e )
1050 // Just return originally-decoded bytes
1051 } // end catch
1052 finally
1054 try{ baos.close(); } catch( Exception e ){}
1055 try{ gzis.close(); } catch( Exception e ){}
1056 try{ bais.close(); } catch( Exception e ){}
1057 } // end finally
1059 } // end if: gzipped
1060 } // end if: bytes.length >= 2
1062 return bytes;
1063 } // end decode
1069 * Attempts to decode Base64 data and deserialize a Java
1070 * Object within. Returns <tt>null</tt> if there was an error.
1072 * @param encodedObject The Base64 data to decode
1073 * @return The decoded and deserialized object
1074 * @since 1.5
1076 public static Object decodeToObject( String encodedObject )
1078 // Decode and gunzip if necessary
1079 byte[] objBytes = decode( encodedObject );
1081 java.io.ByteArrayInputStream bais = null;
1082 java.io.ObjectInputStream ois = null;
1083 Object obj = null;
1087 bais = new java.io.ByteArrayInputStream( objBytes );
1088 ois = new java.io.ObjectInputStream( bais );
1090 obj = ois.readObject();
1091 } // end try
1092 catch( java.io.IOException e )
1094 e.printStackTrace();
1095 obj = null;
1096 } // end catch
1097 catch( java.lang.ClassNotFoundException e )
1099 e.printStackTrace();
1100 obj = null;
1101 } // end catch
1102 finally
1104 try{ bais.close(); } catch( Exception e ){}
1105 try{ ois.close(); } catch( Exception e ){}
1106 } // end finally
1108 return obj;
1109 } // end decodeObject
1114 * Convenience method for encoding data to a file.
1116 * @param dataToEncode byte array of data to encode in base64 form
1117 * @param filename Filename for saving encoded data
1118 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
1120 * @since 2.1
1122 public static boolean encodeToFile( byte[] dataToEncode, String filename )
1124 boolean success = false;
1125 Base64.OutputStream bos = null;
1128 bos = new Base64.OutputStream(
1129 new java.io.FileOutputStream( filename ), Base64.ENCODE );
1130 bos.write( dataToEncode );
1131 success = true;
1132 } // end try
1133 catch( java.io.IOException e )
1136 success = false;
1137 } // end catch: IOException
1138 finally
1140 try{ bos.close(); } catch( Exception e ){}
1141 } // end finally
1143 return success;
1144 } // end encodeToFile
1148 * Convenience method for decoding data to a file.
1150 * @param dataToDecode Base64-encoded data as a string
1151 * @param filename Filename for saving decoded data
1152 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
1154 * @since 2.1
1156 public static boolean decodeToFile( String dataToDecode, String filename )
1158 boolean success = false;
1159 Base64.OutputStream bos = null;
1162 bos = new Base64.OutputStream(
1163 new java.io.FileOutputStream( filename ), Base64.DECODE );
1164 bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
1165 success = true;
1166 } // end try
1167 catch( java.io.IOException e )
1169 success = false;
1170 } // end catch: IOException
1171 finally
1173 try{ bos.close(); } catch( Exception e ){}
1174 } // end finally
1176 return success;
1177 } // end decodeToFile
1183 * Convenience method for reading a base64-encoded
1184 * file and decoding it.
1186 * @param filename Filename for reading encoded data
1187 * @return decoded byte array or null if unsuccessful
1189 * @since 2.1
1191 public static byte[] decodeFromFile( String filename )
1193 byte[] decodedData = null;
1194 Base64.InputStream bis = null;
1197 // Set up some useful variables
1198 java.io.File file = new java.io.File( filename );
1199 byte[] buffer = null;
1200 int length = 0;
1201 int numBytes = 0;
1203 // Check for size of file
1204 if( file.length() > Integer.MAX_VALUE )
1206 System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
1207 return null;
1208 } // end if: file too big for int index
1209 buffer = new byte[ (int)file.length() ];
1211 // Open a stream
1212 bis = new Base64.InputStream(
1213 new java.io.BufferedInputStream(
1214 new java.io.FileInputStream( file ) ), Base64.DECODE );
1216 // Read until done
1217 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
1218 length += numBytes;
1220 // Save in a variable to return
1221 decodedData = new byte[ length ];
1222 System.arraycopy( buffer, 0, decodedData, 0, length );
1224 } // end try
1225 catch( java.io.IOException e )
1227 System.err.println( "Error decoding from file " + filename );
1228 } // end catch: IOException
1229 finally
1231 try{ bis.close(); } catch( Exception e) {}
1232 } // end finally
1234 return decodedData;
1235 } // end decodeFromFile
1240 * Convenience method for reading a binary file
1241 * and base64-encoding it.
1243 * @param filename Filename for reading binary data
1244 * @return base64-encoded string or null if unsuccessful
1246 * @since 2.1
1248 public static String encodeFromFile( String filename )
1250 String encodedData = null;
1251 Base64.InputStream bis = null;
1254 // Set up some useful variables
1255 java.io.File file = new java.io.File( filename );
1256 byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)
1257 int length = 0;
1258 int numBytes = 0;
1260 // Open a stream
1261 bis = new Base64.InputStream(
1262 new java.io.BufferedInputStream(
1263 new java.io.FileInputStream( file ) ), Base64.ENCODE );
1265 // Read until done
1266 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
1267 length += numBytes;
1269 // Save in a variable to return
1270 encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
1272 } // end try
1273 catch( java.io.IOException e )
1275 System.err.println( "Error encoding from file " + filename );
1276 } // end catch: IOException
1277 finally
1279 try{ bis.close(); } catch( Exception e) {}
1280 } // end finally
1282 return encodedData;
1283 } // end encodeFromFile
1289 * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
1291 * @param infile Input file
1292 * @param outfile Output file
1293 * @return true if the operation is successful
1294 * @since 2.2
1296 public static boolean encodeFileToFile( String infile, String outfile )
1298 boolean success = false;
1299 java.io.InputStream in = null;
1300 java.io.OutputStream out = null;
1301 try{
1302 in = new Base64.InputStream(
1303 new java.io.BufferedInputStream(
1304 new java.io.FileInputStream( infile ) ),
1305 Base64.ENCODE );
1306 out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) );
1307 byte[] buffer = new byte[65536]; // 64K
1308 int read = -1;
1309 while( ( read = in.read(buffer) ) >= 0 ){
1310 out.write( buffer,0,read );
1311 } // end while: through file
1312 success = true;
1313 } catch( java.io.IOException exc ){
1314 exc.printStackTrace();
1315 } finally{
1316 try{ in.close(); } catch( Exception exc ){}
1317 try{ out.close(); } catch( Exception exc ){}
1318 } // end finally
1320 return success;
1321 } // end encodeFileToFile
1326 * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
1328 * @param infile Input file
1329 * @param outfile Output file
1330 * @return true if the operation is successful
1331 * @since 2.2
1333 public static boolean decodeFileToFile( String infile, String outfile )
1335 boolean success = false;
1336 java.io.InputStream in = null;
1337 java.io.OutputStream out = null;
1338 try{
1339 in = new Base64.InputStream(
1340 new java.io.BufferedInputStream(
1341 new java.io.FileInputStream( infile ) ),
1342 Base64.DECODE );
1343 out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) );
1344 byte[] buffer = new byte[65536]; // 64K
1345 int read = -1;
1346 while( ( read = in.read(buffer) ) >= 0 ){
1347 out.write( buffer,0,read );
1348 } // end while: through file
1349 success = true;
1350 } catch( java.io.IOException exc ){
1351 exc.printStackTrace();
1352 } finally{
1353 try{ in.close(); } catch( Exception exc ){}
1354 try{ out.close(); } catch( Exception exc ){}
1355 } // end finally
1357 return success;
1358 } // end decodeFileToFile
1361 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
1366 * A {@link Base64.InputStream} will read data from another
1367 * <tt>java.io.InputStream</tt>, given in the constructor,
1368 * and encode/decode to/from Base64 notation on the fly.
1370 * @see Base64
1371 * @since 1.3
1373 public static class InputStream extends java.io.FilterInputStream
1375 private boolean encode; // Encoding or decoding
1376 private int position; // Current position in the buffer
1377 private byte[] buffer; // Small buffer holding converted data
1378 private int bufferLength; // Length of buffer (3 or 4)
1379 private int numSigBytes; // Number of meaningful bytes in the buffer
1380 private int lineLength;
1381 private boolean breakLines; // Break lines at less than 80 characters
1382 private int options; // Record options used to create the stream.
1383 private byte[] alphabet; // Local copies to avoid extra method calls
1384 private byte[] decodabet; // Local copies to avoid extra method calls
1388 * Constructs a {@link Base64.InputStream} in DECODE mode.
1390 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1391 * @since 1.3
1393 public InputStream( java.io.InputStream in )
1395 this( in, DECODE );
1396 } // end constructor
1400 * Constructs a {@link Base64.InputStream} in
1401 * either ENCODE or DECODE mode.
1402 * <p>
1403 * Valid options:<pre>
1404 * ENCODE or DECODE: Encode or Decode as data is read.
1405 * DONT_BREAK_LINES: don't break lines at 76 characters
1406 * (only meaningful when encoding)
1407 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1408 * </pre>
1409 * <p>
1410 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
1413 * @param in the <tt>java.io.InputStream</tt> from which to read data.
1414 * @param options Specified options
1415 * @see Base64#ENCODE
1416 * @see Base64#DECODE
1417 * @see Base64#DONT_BREAK_LINES
1418 * @since 2.0
1420 public InputStream( java.io.InputStream in, int options )
1422 super( in );
1423 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1424 this.encode = (options & ENCODE) == ENCODE;
1425 this.bufferLength = encode ? 4 : 3;
1426 this.buffer = new byte[ bufferLength ];
1427 this.position = -1;
1428 this.lineLength = 0;
1429 this.options = options; // Record for later, mostly to determine which alphabet to use
1430 this.alphabet = getAlphabet(options);
1431 this.decodabet = getDecodabet(options);
1432 } // end constructor
1435 * Reads enough of the input stream to convert
1436 * to/from Base64 and returns the next byte.
1438 * @return next byte
1439 * @since 1.3
1441 public int read() throws java.io.IOException
1443 // Do we need to get data?
1444 if( position < 0 )
1446 if( encode )
1448 byte[] b3 = new byte[3];
1449 int numBinaryBytes = 0;
1450 for( int i = 0; i < 3; i++ )
1454 int b = in.read();
1456 // If end of stream, b is -1.
1457 if( b >= 0 )
1459 b3[i] = (byte)b;
1460 numBinaryBytes++;
1461 } // end if: not end of stream
1463 } // end try: read
1464 catch( java.io.IOException e )
1466 // Only a problem if we got no data at all.
1467 if( i == 0 )
1468 throw e;
1470 } // end catch
1471 } // end for: each needed input byte
1473 if( numBinaryBytes > 0 )
1475 encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
1476 position = 0;
1477 numSigBytes = 4;
1478 } // end if: got data
1479 else
1481 return -1;
1482 } // end else
1483 } // end if: encoding
1485 // Else decoding
1486 else
1488 byte[] b4 = new byte[4];
1489 int i = 0;
1490 for( i = 0; i < 4; i++ )
1492 // Read four "meaningful" bytes:
1493 int b = 0;
1494 do{ b = in.read(); }
1495 while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
1497 if( b < 0 )
1498 break; // Reads a -1 if end of stream
1500 b4[i] = (byte)b;
1501 } // end for: each needed input byte
1503 if( i == 4 )
1505 numSigBytes = decode4to3( b4, 0, buffer, 0, options );
1506 position = 0;
1507 } // end if: got four characters
1508 else if( i == 0 ){
1509 return -1;
1510 } // end else if: also padded correctly
1511 else
1513 // Must have broken out from above.
1514 throw new java.io.IOException( "Improperly padded Base64 input." );
1515 } // end
1517 } // end else: decode
1518 } // end else: get data
1520 // Got data?
1521 if( position >= 0 )
1523 // End of relevant data?
1524 if( /*!encode &&*/ position >= numSigBytes )
1525 return -1;
1527 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
1529 lineLength = 0;
1530 return '\n';
1531 } // end if
1532 else
1534 lineLength++; // This isn't important when decoding
1535 // but throwing an extra "if" seems
1536 // just as wasteful.
1538 int b = buffer[ position++ ];
1540 if( position >= bufferLength )
1541 position = -1;
1543 return b & 0xFF; // This is how you "cast" a byte that's
1544 // intended to be unsigned.
1545 } // end else
1546 } // end if: position >= 0
1548 // Else error
1549 else
1551 // When JDK1.4 is more accepted, use an assertion here.
1552 throw new java.io.IOException( "Error in Base64 code reading stream." );
1553 } // end else
1554 } // end read
1558 * Calls {@link #read()} repeatedly until the end of stream
1559 * is reached or <var>len</var> bytes are read.
1560 * Returns number of bytes read into array or -1 if
1561 * end of stream is encountered.
1563 * @param dest array to hold values
1564 * @param off offset for array
1565 * @param len max number of bytes to read into array
1566 * @return bytes read into array or -1 if end of stream is encountered.
1567 * @since 1.3
1569 public int read( byte[] dest, int off, int len ) throws java.io.IOException
1571 int i;
1572 int b;
1573 for( i = 0; i < len; i++ )
1575 b = read();
1577 //if( b < 0 && i == 0 )
1578 // return -1;
1580 if( b >= 0 )
1581 dest[off + i] = (byte)b;
1582 else if( i == 0 )
1583 return -1;
1584 else
1585 break; // Out of 'for' loop
1586 } // end for: each byte read
1587 return i;
1588 } // end read
1590 } // end inner class InputStream
1597 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
1602 * A {@link Base64.OutputStream} will write data to another
1603 * <tt>java.io.OutputStream</tt>, given in the constructor,
1604 * and encode/decode to/from Base64 notation on the fly.
1606 * @see Base64
1607 * @since 1.3
1609 public static class OutputStream extends java.io.FilterOutputStream
1611 private boolean encode;
1612 private int position;
1613 private byte[] buffer;
1614 private int bufferLength;
1615 private int lineLength;
1616 private boolean breakLines;
1617 private byte[] b4; // Scratch used in a few places
1618 private boolean suspendEncoding;
1619 private int options; // Record for later
1620 private byte[] alphabet; // Local copies to avoid extra method calls
1621 private byte[] decodabet; // Local copies to avoid extra method calls
1624 * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1626 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1627 * @since 1.3
1629 public OutputStream( java.io.OutputStream out )
1631 this( out, ENCODE );
1632 } // end constructor
1636 * Constructs a {@link Base64.OutputStream} in
1637 * either ENCODE or DECODE mode.
1638 * <p>
1639 * Valid options:<pre>
1640 * ENCODE or DECODE: Encode or Decode as data is read.
1641 * DONT_BREAK_LINES: don't break lines at 76 characters
1642 * (only meaningful when encoding)
1643 * <i>Note: Technically, this makes your encoding non-compliant.</i>
1644 * </pre>
1645 * <p>
1646 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
1648 * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
1649 * @param options Specified options.
1650 * @see Base64#ENCODE
1651 * @see Base64#DECODE
1652 * @see Base64#DONT_BREAK_LINES
1653 * @since 1.3
1655 public OutputStream( java.io.OutputStream out, int options )
1657 super( out );
1658 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
1659 this.encode = (options & ENCODE) == ENCODE;
1660 this.bufferLength = encode ? 3 : 4;
1661 this.buffer = new byte[ bufferLength ];
1662 this.position = 0;
1663 this.lineLength = 0;
1664 this.suspendEncoding = false;
1665 this.b4 = new byte[4];
1666 this.options = options;
1667 this.alphabet = getAlphabet(options);
1668 this.decodabet = getDecodabet(options);
1669 } // end constructor
1673 * Writes the byte to the output stream after
1674 * converting to/from Base64 notation.
1675 * When encoding, bytes are buffered three
1676 * at a time before the output stream actually
1677 * gets a write() call.
1678 * When decoding, bytes are buffered four
1679 * at a time.
1681 * @param theByte the byte to write
1682 * @since 1.3
1684 public void write(int theByte) throws java.io.IOException
1686 // Encoding suspended?
1687 if( suspendEncoding )
1689 super.out.write( theByte );
1690 return;
1691 } // end if: supsended
1693 // Encode?
1694 if( encode )
1696 buffer[ position++ ] = (byte)theByte;
1697 if( position >= bufferLength ) // Enough to encode.
1699 out.write( encode3to4( b4, buffer, bufferLength, options ) );
1701 lineLength += 4;
1702 if( breakLines && lineLength >= MAX_LINE_LENGTH )
1704 out.write( NEW_LINE );
1705 lineLength = 0;
1706 } // end if: end of line
1708 position = 0;
1709 } // end if: enough to output
1710 } // end if: encoding
1712 // Else, Decoding
1713 else
1715 // Meaningful Base64 character?
1716 if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC )
1718 buffer[ position++ ] = (byte)theByte;
1719 if( position >= bufferLength ) // Enough to output.
1721 int len = Base64.decode4to3( buffer, 0, b4, 0, options );
1722 out.write( b4, 0, len );
1723 //out.write( Base64.decode4to3( buffer ) );
1724 position = 0;
1725 } // end if: enough to output
1726 } // end if: meaningful base64 character
1727 else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC )
1729 throw new java.io.IOException( "Invalid character in Base64 data." );
1730 } // end else: not white space either
1731 } // end else: decoding
1732 } // end write
1737 * Calls {@link #write(int)} repeatedly until <var>len</var>
1738 * bytes are written.
1740 * @param theBytes array from which to read bytes
1741 * @param off offset for array
1742 * @param len max number of bytes to read into array
1743 * @since 1.3
1745 public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
1747 // Encoding suspended?
1748 if( suspendEncoding )
1750 super.out.write( theBytes, off, len );
1751 return;
1752 } // end if: supsended
1754 for( int i = 0; i < len; i++ )
1756 write( theBytes[ off + i ] );
1757 } // end for: each byte written
1759 } // end write
1764 * Method added by PHIL. [Thanks, PHIL. -Rob]
1765 * This pads the buffer without closing the stream.
1767 public void flushBase64() throws java.io.IOException
1769 if( position > 0 )
1771 if( encode )
1773 out.write( encode3to4( b4, buffer, position, options ) );
1774 position = 0;
1775 } // end if: encoding
1776 else
1778 throw new java.io.IOException( "Base64 input not properly padded." );
1779 } // end else: decoding
1780 } // end if: buffer partially full
1782 } // end flush
1785 /**
1786 * Flushes and closes (I think, in the superclass) the stream.
1788 * @since 1.3
1790 public void close() throws java.io.IOException
1792 // 1. Ensure that pending characters are written
1793 flushBase64();
1795 // 2. Actually close the stream
1796 // Base class both flushes and closes.
1797 super.close();
1799 buffer = null;
1800 out = null;
1801 } // end close
1806 * Suspends encoding of the stream.
1807 * May be helpful if you need to embed a piece of
1808 * base640-encoded data in a stream.
1810 * @since 1.5.1
1812 public void suspendEncoding() throws java.io.IOException
1814 flushBase64();
1815 this.suspendEncoding = true;
1816 } // end suspendEncoding
1820 * Resumes encoding of the stream.
1821 * May be helpful if you need to embed a piece of
1822 * base640-encoded data in a stream.
1824 * @since 1.5.1
1826 public void resumeEncoding()
1828 this.suspendEncoding = false;
1829 } // end resumeEncoding
1833 } // end inner class OutputStream
1836 } // end class Base64