1 /************************************************************** 2 * 3 * Licensed to the Apache Software Foundation (ASF) under one 4 * or more contributor license agreements. See the NOTICE file 5 * distributed with this work for additional information 6 * regarding copyright ownership. The ASF licenses this file 7 * to you under the Apache License, Version 2.0 (the 8 * "License"); you may not use this file except in compliance 9 * with the License. You may obtain a copy of the License at 10 * 11 * http://www.apache.org/licenses/LICENSE-2.0 12 * 13 * Unless required by applicable law or agreed to in writing, 14 * software distributed under the License is distributed on an 15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 * KIND, either express or implied. See the License for the 17 * specific language governing permissions and limitations 18 * under the License. 19 * 20 *************************************************************/ 21 22 package com.sun.star.comp.xsltfilter; 23 24 25 /** 26 * <p>Encodes and decodes to and from Base64 notation.</p> 27 * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> 28 * 29 * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass 30 * several pieces of information to the encoder. In the "higher level" methods such as 31 * encodeBytes( bytes, options ) the options parameter can be used to indicate such 32 * things as first gzipping the bytes before encoding them, not inserting linefeeds 33 * (though that breaks strict Base64 compatibility), and encoding using the URL-safe 34 * and Ordered dialects.</p> 35 * 36 * <p>The constants defined in Base64 can be OR-ed together to combine options, so you 37 * might make a call like this:</p> 38 * 39 * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DONT_BREAK_LINES );</code> 40 * 41 * <p>to compress the data before encoding it and then making the output have no newline characters.</p> 42 * 43 * 44 * <p> 45 * Change Log: 46 * </p> 47 * <ul> 48 * <li>v2.2.2 - Fixed encodeFileToFile and decodeFileToFile to use the 49 * Base64.InputStream class to encode and decode on the fly which uses 50 * less memory than encoding/decoding an entire file into memory before writing.</li> 51 * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug 52 * when using very small files (~< 40 bytes).</li> 53 * <li>v2.2 - Added some helper methods for encoding/decoding directly from 54 * one file to the next. Also added a main() method to support command line 55 * encoding/decoding from one file to the next. Also added these Base64 dialects: 56 * <ol> 57 * <li>The default is RFC3548 format.</li> 58 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates 59 * URL and file name friendly format as described in Section 4 of RFC3548. 60 * http://www.faqs.org/rfcs/rfc3548.html</li> 61 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates 62 * URL and file name friendly format that preserves lexical ordering as described 63 * in http://www.faqs.org/qa/rfcc-1940.html</li> 64 * </ol> 65 * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> 66 * for contributing the new Base64 dialects. 67 * </li> 68 * 69 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added 70 * some convenience methods for reading and writing to and from files.</li> 71 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems 72 * with other encodings (like EBCDIC).</li> 73 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the 74 * encoded data was a single byte.</li> 75 * <li>v2.0 - I got rid of methods that used booleans to set options. 76 * Now everything is more consolidated and cleaner. The code now detects 77 * when data that's being decoded is gzip-compressed and will decompress it 78 * automatically. Generally things are cleaner. You'll probably have to 79 * change some method calls that you were making to support the new 80 * options format (<tt>int</tt>s that you "OR" together).</li> 81 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a 82 * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. 83 * Added the ability to "suspend" encoding in the Output Stream so 84 * you can turn on and off the encoding if you need to embed base64 85 * data in an otherwise "normal" stream (like an XML file).</li> 86 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. 87 * This helps when using GZIP streams. 88 * Added the ability to GZip-compress objects before encoding them.</li> 89 * <li>v1.4 - Added helper methods to read/write files.</li> 90 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> 91 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream 92 * where last buffer being read, if not completely full, was not returned.</li> 93 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> 94 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> 95 * </ul> 96 * 97 * <p> 98 * I am placing this code in the Public Domain. Do with it as you will. 99 * This software comes with no guarantees or warranties but with 100 * plenty of well-wishing instead! 101 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> 102 * periodically to check for updates or to contribute improvements. 103 * </p> 104 * 105 * @author Robert Harder 106 * @author rob@iharder.net 107 * @version 2.2.2 108 */ 109 public class Base64 110 { 111 112 /* ******** P U B L I C F I E L D S ******** */ 113 114 115 /** No options specified. Value is zero. */ 116 public final static int NO_OPTIONS = 0; 117 118 /** Specify encoding. */ 119 public final static int ENCODE = 1; 120 121 122 /** Specify decoding. */ 123 public final static int DECODE = 0; 124 125 126 /** Specify that data should be gzip-compressed. */ 127 public final static int GZIP = 2; 128 129 130 /** Don't break lines when encoding (violates strict Base64 specification) */ 131 public final static int DONT_BREAK_LINES = 8; 132 133 /** 134 * Encode using Base64-like encoding that is URL- and Filename-safe as described 135 * in Section 4 of RFC3548: 136 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. 137 * It is important to note that data encoded this way is <em>not</em> officially valid Base64, 138 * or at the very least should not be called Base64 without also specifying that is 139 * was encoded using the URL- and Filename-safe dialect. 140 */ 141 public final static int URL_SAFE = 16; 142 143 144 /** 145 * Encode using the special "ordered" dialect of Base64 described here: 146 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. 147 */ 148 public final static int ORDERED = 32; 149 150 151 /* ******** P R I V A T E F I E L D S ******** */ 152 153 154 /** Maximum line length (76) of Base64 output. */ 155 private final static int MAX_LINE_LENGTH = 76; 156 157 158 /** The equals sign (=) as a byte. */ 159 private final static byte EQUALS_SIGN = (byte)'='; 160 161 162 /** The new line character (\n) as a byte. */ 163 private final static byte NEW_LINE = (byte)'\n'; 164 165 166 /** Preferred encoding. */ 167 private final static String PREFERRED_ENCODING = "UTF-8"; 168 169 170 // I think I end up not using the BAD_ENCODING indicator. 171 //private final static byte BAD_ENCODING = -9; // Indicates error in encoding 172 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding 173 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding 174 175 176 /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ 177 178 /** The 64 valid Base64 values. */ 179 //private final static byte[] ALPHABET; 180 /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ 181 private final static byte[] _STANDARD_ALPHABET = 182 { 183 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 184 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 185 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 186 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 187 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 188 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 189 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 190 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', 191 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 192 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' 193 }; 194 195 196 /** 197 * Translates a Base64 value to either its 6-bit reconstruction value 198 * or a negative number indicating some other meaning. 199 **/ 200 private final static byte[] _STANDARD_DECODABET = 201 { 202 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 203 -5,-5, // Whitespace: Tab and Linefeed 204 -9,-9, // Decimal 11 - 12 205 -5, // Whitespace: Carriage Return 206 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 207 -9,-9,-9,-9,-9, // Decimal 27 - 31 208 -5, // Whitespace: Space 209 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 210 62, // Plus sign at decimal 43 211 -9,-9,-9, // Decimal 44 - 46 212 63, // Slash at decimal 47 213 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine 214 -9,-9,-9, // Decimal 58 - 60 215 -1, // Equals sign at decimal 61 216 -9,-9,-9, // Decimal 62 - 64 217 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 218 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' 219 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 220 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 221 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' 222 -9,-9,-9,-9 // Decimal 123 - 126 223 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 224 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 225 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 226 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 227 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 228 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 229 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 231 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 232 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 233 }; 234 235 236 /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ 237 238 /** 239 * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: 240 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. 241 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." 242 */ 243 private final static byte[] _URL_SAFE_ALPHABET = 244 { 245 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 246 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 247 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 248 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 249 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 250 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 251 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 252 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', 253 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 254 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' 255 }; 256 257 /** 258 * Used in decoding URL- and Filename-safe dialects of Base64. 259 */ 260 private final static byte[] _URL_SAFE_DECODABET = 261 { 262 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 263 -5,-5, // Whitespace: Tab and Linefeed 264 -9,-9, // Decimal 11 - 12 265 -5, // Whitespace: Carriage Return 266 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 267 -9,-9,-9,-9,-9, // Decimal 27 - 31 268 -5, // Whitespace: Space 269 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 270 -9, // Plus sign at decimal 43 271 -9, // Decimal 44 272 62, // Minus sign at decimal 45 273 -9, // Decimal 46 274 -9, // Slash at decimal 47 275 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine 276 -9,-9,-9, // Decimal 58 - 60 277 -1, // Equals sign at decimal 61 278 -9,-9,-9, // Decimal 62 - 64 279 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 280 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' 281 -9,-9,-9,-9, // Decimal 91 - 94 282 63, // Underscore at decimal 95 283 -9, // Decimal 96 284 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 285 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' 286 -9,-9,-9,-9 // Decimal 123 - 126 287 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 288 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 289 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 290 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 291 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 292 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 293 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 294 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 295 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 296 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 297 }; 298 299 300 301 /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ 302 303 /** 304 * I don't get the point of this technique, but it is described here: 305 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. 306 */ 307 private final static byte[] _ORDERED_ALPHABET = 308 { 309 (byte)'-', 310 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', 311 (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', 312 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 313 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 314 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 315 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 316 (byte)'_', 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 }; 322 323 /** 324 * Used in decoding the "ordered" dialect of Base64. 325 */ 326 private final static byte[] _ORDERED_DECODABET = 327 { 328 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 329 -5,-5, // Whitespace: Tab and Linefeed 330 -9,-9, // Decimal 11 - 12 331 -5, // Whitespace: Carriage Return 332 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 333 -9,-9,-9,-9,-9, // Decimal 27 - 31 334 -5, // Whitespace: Space 335 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 336 -9, // Plus sign at decimal 43 337 -9, // Decimal 44 338 0, // Minus sign at decimal 45 339 -9, // Decimal 46 340 -9, // Slash at decimal 47 341 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine 342 -9,-9,-9, // Decimal 58 - 60 343 -1, // Equals sign at decimal 61 344 -9,-9,-9, // Decimal 62 - 64 345 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 346 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' 347 -9,-9,-9,-9, // Decimal 91 - 94 348 37, // Underscore at decimal 95 349 -9, // Decimal 96 350 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 351 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' 352 -9,-9,-9,-9 // Decimal 123 - 126 353 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 354 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 355 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 356 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 357 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 358 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 359 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 360 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 361 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 362 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 363 }; 364 365 366 /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ 367 368 369 /** 370 * Returns one of the _SOMETHING_ALPHABET byte arrays depending on 371 * the options specified. 372 * It's possible, though silly, to specify ORDERED and URLSAFE 373 * in which case one of them will be picked, though there is 374 * no guarantee as to which one will be picked. 375 */ getAlphabet( int options )376 private final static byte[] getAlphabet( int options ) 377 { 378 if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET; 379 else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET; 380 else return _STANDARD_ALPHABET; 381 382 } // end getAlphabet 383 384 385 /** 386 * Returns one of the _SOMETHING_DECODABET byte arrays depending on 387 * the options specified. 388 * It's possible, though silly, to specify ORDERED and URL_SAFE 389 * in which case one of them will be picked, though there is 390 * no guarantee as to which one will be picked. 391 */ getDecodabet( int options )392 private final static byte[] getDecodabet( int options ) 393 { 394 if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET; 395 else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET; 396 else return _STANDARD_DECODABET; 397 398 } // end getAlphabet 399 400 401 402 /** Defeats instantiation. */ Base64()403 private Base64(){} 404 405 406 /** 407 * Encodes or decodes two files from the command line; 408 * <strong>feel free to delete this method (in fact you probably should) 409 * if you're embedding this code into a larger program.</strong> 410 */ main( String[] args )411 public final static void main( String[] args ) 412 { 413 if( args.length < 3 ){ 414 usage("Not enough arguments."); 415 } // end if: args.length < 3 416 else { 417 String flag = args[0]; 418 String infile = args[1]; 419 String outfile = args[2]; 420 if( flag.equals( "-e" ) ){ 421 Base64.encodeFileToFile( infile, outfile ); 422 } // end if: encode 423 else if( flag.equals( "-d" ) ) { 424 Base64.decodeFileToFile( infile, outfile ); 425 } // end else if: decode 426 else { 427 usage( "Unknown flag: " + flag ); 428 } // end else 429 } // end else 430 } // end main 431 432 /** 433 * Prints command line usage. 434 * 435 * @param msg A message to include with usage info. 436 */ usage( String msg )437 private final static void usage( String msg ) 438 { 439 System.err.println( msg ); 440 System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" ); 441 } // end usage 442 443 444 /* ******** E N C O D I N G M E T H O D S ******** */ 445 446 447 /** 448 * Encodes up to the first three bytes of array <var>threeBytes</var> 449 * and returns a four-byte array in Base64 notation. 450 * The actual number of significant bytes in your array is 451 * given by <var>numSigBytes</var>. 452 * The array <var>threeBytes</var> needs only be as big as 453 * <var>numSigBytes</var>. 454 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. 455 * 456 * @param b4 A reusable byte array to reduce array instantiation 457 * @param threeBytes the array to convert 458 * @param numSigBytes the number of significant bytes in your array 459 * @return four byte array in Base64 notation. 460 * @since 1.5.1 461 */ encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options )462 private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) 463 { 464 encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); 465 return b4; 466 } // end encode3to4 467 468 469 /** 470 * <p>Encodes up to three bytes of the array <var>source</var> 471 * and writes the resulting four Base64 bytes to <var>destination</var>. 472 * The source and destination arrays can be manipulated 473 * anywhere along their length by specifying 474 * <var>srcOffset</var> and <var>destOffset</var>. 475 * This method does not check to make sure your arrays 476 * are large enough to accomodate <var>srcOffset</var> + 3 for 477 * the <var>source</var> array or <var>destOffset</var> + 4 for 478 * the <var>destination</var> array. 479 * The actual number of significant bytes in your array is 480 * given by <var>numSigBytes</var>.</p> 481 * <p>This is the lowest level of the encoding methods with 482 * all possible parameters.</p> 483 * 484 * @param source the array to convert 485 * @param srcOffset the index where conversion begins 486 * @param numSigBytes the number of significant bytes in your array 487 * @param destination the array to hold the conversion 488 * @param destOffset the index where output will be put 489 * @return the <var>destination</var> array 490 * @since 1.3 491 */ encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options )492 private static byte[] encode3to4( 493 byte[] source, int srcOffset, int numSigBytes, 494 byte[] destination, int destOffset, int options ) 495 { 496 byte[] ALPHABET = getAlphabet( options ); 497 498 // 1 2 3 499 // 01234567890123456789012345678901 Bit position 500 // --------000000001111111122222222 Array position from threeBytes 501 // --------| || || || | Six bit groups to index ALPHABET 502 // >>18 >>12 >> 6 >> 0 Right shift necessary 503 // 0x3f 0x3f 0x3f Additional AND 504 505 // Create buffer with zero-padding if there are only one or two 506 // significant bytes passed in the array. 507 // We have to shift left 24 in order to flush out the 1's that appear 508 // when Java treats a value as negative that is cast from a byte to an int. 509 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) 510 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) 511 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); 512 513 switch( numSigBytes ) 514 { 515 case 3: 516 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 517 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 518 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; 519 destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; 520 return destination; 521 522 case 2: 523 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 524 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 525 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; 526 destination[ destOffset + 3 ] = EQUALS_SIGN; 527 return destination; 528 529 case 1: 530 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 531 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 532 destination[ destOffset + 2 ] = EQUALS_SIGN; 533 destination[ destOffset + 3 ] = EQUALS_SIGN; 534 return destination; 535 536 default: 537 return destination; 538 } // end switch 539 } // end encode3to4 540 541 542 543 /** 544 * Serializes an object and returns the Base64-encoded 545 * version of that serialized object. If the object 546 * cannot be serialized or there is another error, 547 * the method will return <tt>null</tt>. 548 * The object is not GZip-compressed before being encoded. 549 * 550 * @param serializableObject The object to encode 551 * @return The Base64-encoded object 552 * @since 1.4 553 */ encodeObject( java.io.Serializable serializableObject )554 public static String encodeObject( java.io.Serializable serializableObject ) 555 { 556 return encodeObject( serializableObject, NO_OPTIONS ); 557 } // end encodeObject 558 559 560 561 /** 562 * Serializes an object and returns the Base64-encoded 563 * version of that serialized object. If the object 564 * cannot be serialized or there is another error, 565 * the method will return <tt>null</tt>. 566 * <p> 567 * Valid options:<pre> 568 * GZIP: gzip-compresses object before encoding it. 569 * DONT_BREAK_LINES: don't break lines at 76 characters 570 * <i>Note: Technically, this makes your encoding non-compliant.</i> 571 * </pre> 572 * <p> 573 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or 574 * <p> 575 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> 576 * 577 * @param serializableObject The object to encode 578 * @param options Specified options 579 * @return The Base64-encoded object 580 * @see Base64#GZIP 581 * @see Base64#DONT_BREAK_LINES 582 * @since 2.0 583 */ encodeObject( java.io.Serializable serializableObject, int options )584 public static String encodeObject( java.io.Serializable serializableObject, int options ) 585 { 586 // Streams 587 java.io.ByteArrayOutputStream baos = null; 588 java.io.OutputStream b64os = null; 589 java.io.ObjectOutputStream oos = null; 590 java.util.zip.GZIPOutputStream gzos = null; 591 592 // Isolate options 593 int gzip = (options & GZIP); 594 int dontBreakLines = (options & DONT_BREAK_LINES); 595 596 try 597 { 598 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream 599 baos = new java.io.ByteArrayOutputStream(); 600 b64os = new Base64.OutputStream( baos, ENCODE | options ); 601 602 // GZip? 603 if( gzip == GZIP ) 604 { 605 gzos = new java.util.zip.GZIPOutputStream( b64os ); 606 oos = new java.io.ObjectOutputStream( gzos ); 607 } // end if: gzip 608 else 609 oos = new java.io.ObjectOutputStream( b64os ); 610 611 oos.writeObject( serializableObject ); 612 } // end try 613 catch( java.io.IOException e ) 614 { 615 e.printStackTrace(); 616 return null; 617 } // end catch 618 finally 619 { 620 try{ oos.close(); } catch( Exception e ){} 621 try{ gzos.close(); } catch( Exception e ){} 622 try{ b64os.close(); } catch( Exception e ){} 623 try{ baos.close(); } catch( Exception e ){} 624 } // end finally 625 626 // Return value according to relevant encoding. 627 try 628 { 629 return new String( baos.toByteArray(), PREFERRED_ENCODING ); 630 } // end try 631 catch (java.io.UnsupportedEncodingException uue) 632 { 633 return new String( baos.toByteArray() ); 634 } // end catch 635 636 } // end encode 637 638 639 640 /** 641 * Encodes a byte array into Base64 notation. 642 * Does not GZip-compress data. 643 * 644 * @param source The data to convert 645 * @since 1.4 646 */ encodeBytes( byte[] source )647 public static String encodeBytes( byte[] source ) 648 { 649 return encodeBytes( source, 0, source.length, NO_OPTIONS ); 650 } // end encodeBytes 651 652 653 654 /** 655 * Encodes a byte array into Base64 notation. 656 * <p> 657 * Valid options:<pre> 658 * GZIP: gzip-compresses object before encoding it. 659 * DONT_BREAK_LINES: don't break lines at 76 characters 660 * <i>Note: Technically, this makes your encoding non-compliant.</i> 661 * </pre> 662 * <p> 663 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or 664 * <p> 665 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> 666 * 667 * 668 * @param source The data to convert 669 * @param options Specified options 670 * @see Base64#GZIP 671 * @see Base64#DONT_BREAK_LINES 672 * @since 2.0 673 */ encodeBytes( byte[] source, int options )674 public static String encodeBytes( byte[] source, int options ) 675 { 676 return encodeBytes( source, 0, source.length, options ); 677 } // end encodeBytes 678 679 680 /** 681 * Encodes a byte array into Base64 notation. 682 * Does not GZip-compress data. 683 * 684 * @param source The data to convert 685 * @param off Offset in array where conversion should begin 686 * @param len Length of data to convert 687 * @since 1.4 688 */ encodeBytes( byte[] source, int off, int len )689 public static String encodeBytes( byte[] source, int off, int len ) 690 { 691 return encodeBytes( source, off, len, NO_OPTIONS ); 692 } // end encodeBytes 693 694 695 696 /** 697 * Encodes a byte array into Base64 notation. 698 * <p> 699 * Valid options:<pre> 700 * GZIP: gzip-compresses object before encoding it. 701 * DONT_BREAK_LINES: don't break lines at 76 characters 702 * <i>Note: Technically, this makes your encoding non-compliant.</i> 703 * </pre> 704 * <p> 705 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or 706 * <p> 707 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> 708 * 709 * 710 * @param source The data to convert 711 * @param off Offset in array where conversion should begin 712 * @param len Length of data to convert 713 * @param options Specified options 714 * @param options alphabet type is pulled from this (standard, url-safe, ordered) 715 * @see Base64#GZIP 716 * @see Base64#DONT_BREAK_LINES 717 * @since 2.0 718 */ encodeBytes( byte[] source, int off, int len, int options )719 public static String encodeBytes( byte[] source, int off, int len, int options ) 720 { 721 // Isolate options 722 int dontBreakLines = ( options & DONT_BREAK_LINES ); 723 int gzip = ( options & GZIP ); 724 725 // Compress? 726 if( gzip == GZIP ) 727 { 728 java.io.ByteArrayOutputStream baos = null; 729 java.util.zip.GZIPOutputStream gzos = null; 730 Base64.OutputStream b64os = null; 731 732 733 try 734 { 735 // GZip -> Base64 -> ByteArray 736 baos = new java.io.ByteArrayOutputStream(); 737 b64os = new Base64.OutputStream( baos, ENCODE | options ); 738 gzos = new java.util.zip.GZIPOutputStream( b64os ); 739 740 gzos.write( source, off, len ); 741 gzos.close(); 742 } // end try 743 catch( java.io.IOException e ) 744 { 745 e.printStackTrace(); 746 return null; 747 } // end catch 748 finally 749 { 750 try{ gzos.close(); } catch( Exception e ){} 751 try{ b64os.close(); } catch( Exception e ){} 752 try{ baos.close(); } catch( Exception e ){} 753 } // end finally 754 755 // Return value according to relevant encoding. 756 try 757 { 758 return new String( baos.toByteArray(), PREFERRED_ENCODING ); 759 } // end try 760 catch (java.io.UnsupportedEncodingException uue) 761 { 762 return new String( baos.toByteArray() ); 763 } // end catch 764 } // end if: compress 765 766 // Else, don't compress. Better not to use streams at all then. 767 else 768 { 769 // Convert option to boolean in way that code likes it. 770 boolean breakLines = dontBreakLines == 0; 771 772 int len43 = len * 4 / 3; 773 byte[] outBuff = new byte[ ( len43 ) // Main 4:3 774 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding 775 + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines 776 int d = 0; 777 int e = 0; 778 int len2 = len - 2; 779 int lineLength = 0; 780 for( ; d < len2; d+=3, e+=4 ) 781 { 782 encode3to4( source, d+off, 3, outBuff, e, options ); 783 784 lineLength += 4; 785 if( breakLines && lineLength == MAX_LINE_LENGTH ) 786 { 787 outBuff[e+4] = NEW_LINE; 788 e++; 789 lineLength = 0; 790 } // end if: end of line 791 } // en dfor: each piece of array 792 793 if( d < len ) 794 { 795 encode3to4( source, d+off, len - d, outBuff, e, options ); 796 e += 4; 797 } // end if: some padding needed 798 799 800 // Return value according to relevant encoding. 801 try 802 { 803 return new String( outBuff, 0, e, PREFERRED_ENCODING ); 804 } // end try 805 catch (java.io.UnsupportedEncodingException uue) 806 { 807 return new String( outBuff, 0, e ); 808 } // end catch 809 810 } // end else: don't compress 811 812 } // end encodeBytes 813 814 815 816 817 818 /* ******** D E C O D I N G M E T H O D S ******** */ 819 820 821 /** 822 * Decodes four bytes from array <var>source</var> 823 * and writes the resulting bytes (up to three of them) 824 * to <var>destination</var>. 825 * The source and destination arrays can be manipulated 826 * anywhere along their length by specifying 827 * <var>srcOffset</var> and <var>destOffset</var>. 828 * This method does not check to make sure your arrays 829 * are large enough to accomodate <var>srcOffset</var> + 4 for 830 * the <var>source</var> array or <var>destOffset</var> + 3 for 831 * the <var>destination</var> array. 832 * This method returns the actual number of bytes that 833 * were converted from the Base64 encoding. 834 * <p>This is the lowest level of the decoding methods with 835 * all possible parameters.</p> 836 * 837 * 838 * @param source the array to convert 839 * @param srcOffset the index where conversion begins 840 * @param destination the array to hold the conversion 841 * @param destOffset the index where output will be put 842 * @param options alphabet type is pulled from this (standard, url-safe, ordered) 843 * @return the number of decoded bytes converted 844 * @since 1.3 845 */ decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options )846 private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) 847 { 848 byte[] DECODABET = getDecodabet( options ); 849 850 // Example: Dk== 851 if( source[ srcOffset + 2] == EQUALS_SIGN ) 852 { 853 // Two ways to do the same thing. Don't know which way I like best. 854 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 855 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); 856 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 857 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); 858 859 destination[ destOffset ] = (byte)( outBuff >>> 16 ); 860 return 1; 861 } 862 863 // Example: DkL= 864 else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) 865 { 866 // Two ways to do the same thing. Don't know which way I like best. 867 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 868 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 869 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); 870 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 871 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) 872 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); 873 874 destination[ destOffset ] = (byte)( outBuff >>> 16 ); 875 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); 876 return 2; 877 } 878 879 // Example: DkLE 880 else 881 { 882 try{ 883 // Two ways to do the same thing. Don't know which way I like best. 884 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 885 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 886 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) 887 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); 888 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 889 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) 890 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) 891 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); 892 893 894 destination[ destOffset ] = (byte)( outBuff >> 16 ); 895 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); 896 destination[ destOffset + 2 ] = (byte)( outBuff ); 897 898 return 3; 899 }catch( Exception e){ 900 System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); 901 System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); 902 System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); 903 System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); 904 return -1; 905 } // end catch 906 } 907 } // end decodeToBytes 908 909 910 911 912 /** 913 * Very low-level access to decoding ASCII characters in 914 * the form of a byte array. Does not support automatically 915 * gunzipping or any other "fancy" features. 916 * 917 * @param source The Base64 encoded data 918 * @param off The offset of where to begin decoding 919 * @param len The length of characters to decode 920 * @return decoded data 921 * @since 1.3 922 */ decode( byte[] source, int off, int len, int options )923 public static byte[] decode( byte[] source, int off, int len, int options ) 924 { 925 byte[] DECODABET = getDecodabet( options ); 926 927 int len34 = len * 3 / 4; 928 byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output 929 int outBuffPosn = 0; 930 931 byte[] b4 = new byte[4]; 932 int b4Posn = 0; 933 int i = 0; 934 byte sbiCrop = 0; 935 byte sbiDecode = 0; 936 for( i = off; i < off+len; i++ ) 937 { 938 sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits 939 sbiDecode = DECODABET[ sbiCrop ]; 940 941 if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better 942 { 943 if( sbiDecode >= EQUALS_SIGN_ENC ) 944 { 945 b4[ b4Posn++ ] = sbiCrop; 946 if( b4Posn > 3 ) 947 { 948 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); 949 b4Posn = 0; 950 951 // If that was the equals sign, break out of 'for' loop 952 if( sbiCrop == EQUALS_SIGN ) 953 break; 954 } // end if: quartet built 955 956 } // end if: equals sign or better 957 958 } // end if: white space, equals sign or better 959 else 960 { 961 System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); 962 return null; 963 } // end else: 964 } // each input character 965 966 byte[] out = new byte[ outBuffPosn ]; 967 System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); 968 return out; 969 } // end decode 970 971 972 973 974 /** 975 * Decodes data from Base64 notation, automatically 976 * detecting gzip-compressed data and decompressing it. 977 * 978 * @param s the string to decode 979 * @return the decoded data 980 * @since 1.4 981 */ decode( String s )982 public static byte[] decode( String s ) 983 { 984 return decode( s, NO_OPTIONS ); 985 } 986 987 988 /** 989 * Decodes data from Base64 notation, automatically 990 * detecting gzip-compressed data and decompressing it. 991 * 992 * @param s the string to decode 993 * @param options encode options such as URL_SAFE 994 * @return the decoded data 995 * @since 1.4 996 */ decode( String s, int options )997 public static byte[] decode( String s, int options ) 998 { 999 byte[] bytes; 1000 try 1001 { 1002 bytes = s.getBytes( PREFERRED_ENCODING ); 1003 } // end try 1004 catch( java.io.UnsupportedEncodingException uee ) 1005 { 1006 bytes = s.getBytes(); 1007 } // end catch 1008 //</change> 1009 1010 // Decode 1011 bytes = decode( bytes, 0, bytes.length, options ); 1012 1013 1014 // Check to see if it's gzip-compressed 1015 // GZIP Magic Two-Byte Number: 0x8b1f (35615) 1016 if( bytes != null && bytes.length >= 4 ) 1017 { 1018 1019 int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); 1020 if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) 1021 { 1022 java.io.ByteArrayInputStream bais = null; 1023 java.util.zip.GZIPInputStream gzis = null; 1024 java.io.ByteArrayOutputStream baos = null; 1025 byte[] buffer = new byte[2048]; 1026 int length = 0; 1027 1028 try 1029 { 1030 baos = new java.io.ByteArrayOutputStream(); 1031 bais = new java.io.ByteArrayInputStream( bytes ); 1032 gzis = new java.util.zip.GZIPInputStream( bais ); 1033 1034 while( ( length = gzis.read( buffer ) ) >= 0 ) 1035 { 1036 baos.write(buffer,0,length); 1037 } // end while: reading input 1038 1039 // No error? Get new bytes. 1040 bytes = baos.toByteArray(); 1041 1042 } // end try 1043 catch( java.io.IOException e ) 1044 { 1045 // Just return originally-decoded bytes 1046 } // end catch 1047 finally 1048 { 1049 try{ baos.close(); } catch( Exception e ){} 1050 try{ gzis.close(); } catch( Exception e ){} 1051 try{ bais.close(); } catch( Exception e ){} 1052 } // end finally 1053 1054 } // end if: gzipped 1055 } // end if: bytes.length >= 2 1056 1057 return bytes; 1058 } // end decode 1059 1060 1061 1062 1063 /** 1064 * Attempts to decode Base64 data and deserialize a Java 1065 * Object within. Returns <tt>null</tt> if there was an error. 1066 * 1067 * @param encodedObject The Base64 data to decode 1068 * @return The decoded and deserialized object 1069 * @since 1.5 1070 */ decodeToObject( String encodedObject )1071 public static Object decodeToObject( String encodedObject ) 1072 { 1073 // Decode and gunzip if necessary 1074 byte[] objBytes = decode( encodedObject ); 1075 1076 java.io.ByteArrayInputStream bais = null; 1077 java.io.ObjectInputStream ois = null; 1078 Object obj = null; 1079 1080 try 1081 { 1082 bais = new java.io.ByteArrayInputStream( objBytes ); 1083 ois = new java.io.ObjectInputStream( bais ); 1084 1085 obj = ois.readObject(); 1086 } // end try 1087 catch( java.io.IOException e ) 1088 { 1089 e.printStackTrace(); 1090 obj = null; 1091 } // end catch 1092 catch( java.lang.ClassNotFoundException e ) 1093 { 1094 e.printStackTrace(); 1095 obj = null; 1096 } // end catch 1097 finally 1098 { 1099 try{ bais.close(); } catch( Exception e ){} 1100 try{ ois.close(); } catch( Exception e ){} 1101 } // end finally 1102 1103 return obj; 1104 } // end decodeObject 1105 1106 1107 1108 /** 1109 * Convenience method for encoding data to a file. 1110 * 1111 * @param dataToEncode byte array of data to encode in base64 form 1112 * @param filename Filename for saving encoded data 1113 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise 1114 * 1115 * @since 2.1 1116 */ encodeToFile( byte[] dataToEncode, String filename )1117 public static boolean encodeToFile( byte[] dataToEncode, String filename ) 1118 { 1119 boolean success = false; 1120 Base64.OutputStream bos = null; 1121 try 1122 { 1123 bos = new Base64.OutputStream( 1124 new java.io.FileOutputStream( filename ), Base64.ENCODE ); 1125 bos.write( dataToEncode ); 1126 success = true; 1127 } // end try 1128 catch( java.io.IOException e ) 1129 { 1130 1131 success = false; 1132 } // end catch: IOException 1133 finally 1134 { 1135 try{ bos.close(); } catch( Exception e ){} 1136 } // end finally 1137 1138 return success; 1139 } // end encodeToFile 1140 1141 1142 /** 1143 * Convenience method for decoding data to a file. 1144 * 1145 * @param dataToDecode Base64-encoded data as a string 1146 * @param filename Filename for saving decoded data 1147 * @return <tt>true</tt> if successful, <tt>false</tt> otherwise 1148 * 1149 * @since 2.1 1150 */ decodeToFile( String dataToDecode, String filename )1151 public static boolean decodeToFile( String dataToDecode, String filename ) 1152 { 1153 boolean success = false; 1154 Base64.OutputStream bos = null; 1155 try 1156 { 1157 bos = new Base64.OutputStream( 1158 new java.io.FileOutputStream( filename ), Base64.DECODE ); 1159 bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); 1160 success = true; 1161 } // end try 1162 catch( java.io.IOException e ) 1163 { 1164 success = false; 1165 } // end catch: IOException 1166 finally 1167 { 1168 try{ bos.close(); } catch( Exception e ){} 1169 } // end finally 1170 1171 return success; 1172 } // end decodeToFile 1173 1174 1175 1176 1177 /** 1178 * Convenience method for reading a base64-encoded 1179 * file and decoding it. 1180 * 1181 * @param filename Filename for reading encoded data 1182 * @return decoded byte array or null if unsuccessful 1183 * 1184 * @since 2.1 1185 */ decodeFromFile( String filename )1186 public static byte[] decodeFromFile( String filename ) 1187 { 1188 byte[] decodedData = null; 1189 Base64.InputStream bis = null; 1190 try 1191 { 1192 // Set up some useful variables 1193 java.io.File file = new java.io.File( filename ); 1194 byte[] buffer = null; 1195 int length = 0; 1196 int numBytes = 0; 1197 1198 // Check for size of file 1199 if( file.length() > Integer.MAX_VALUE ) 1200 { 1201 System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); 1202 return null; 1203 } // end if: file too big for int index 1204 buffer = new byte[ (int)file.length() ]; 1205 1206 // Open a stream 1207 bis = new Base64.InputStream( 1208 new java.io.BufferedInputStream( 1209 new java.io.FileInputStream( file ) ), Base64.DECODE ); 1210 1211 // Read until done 1212 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) 1213 length += numBytes; 1214 1215 // Save in a variable to return 1216 decodedData = new byte[ length ]; 1217 System.arraycopy( buffer, 0, decodedData, 0, length ); 1218 1219 } // end try 1220 catch( java.io.IOException e ) 1221 { 1222 System.err.println( "Error decoding from file " + filename ); 1223 } // end catch: IOException 1224 finally 1225 { 1226 try{ bis.close(); } catch( Exception e) {} 1227 } // end finally 1228 1229 return decodedData; 1230 } // end decodeFromFile 1231 1232 1233 1234 /** 1235 * Convenience method for reading a binary file 1236 * and base64-encoding it. 1237 * 1238 * @param filename Filename for reading binary data 1239 * @return base64-encoded string or null if unsuccessful 1240 * 1241 * @since 2.1 1242 */ encodeFromFile( String filename )1243 public static String encodeFromFile( String filename ) 1244 { 1245 String encodedData = null; 1246 Base64.InputStream bis = null; 1247 try 1248 { 1249 // Set up some useful variables 1250 java.io.File file = new java.io.File( filename ); 1251 byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1) 1252 int length = 0; 1253 int numBytes = 0; 1254 1255 // Open a stream 1256 bis = new Base64.InputStream( 1257 new java.io.BufferedInputStream( 1258 new java.io.FileInputStream( file ) ), Base64.ENCODE ); 1259 1260 // Read until done 1261 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) 1262 length += numBytes; 1263 1264 // Save in a variable to return 1265 encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); 1266 1267 } // end try 1268 catch( java.io.IOException e ) 1269 { 1270 System.err.println( "Error encoding from file " + filename ); 1271 } // end catch: IOException 1272 finally 1273 { 1274 try{ bis.close(); } catch( Exception e) {} 1275 } // end finally 1276 1277 return encodedData; 1278 } // end encodeFromFile 1279 1280 1281 1282 1283 /** 1284 * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. 1285 * 1286 * @param infile Input file 1287 * @param outfile Output file 1288 * @return true if the operation is successful 1289 * @since 2.2 1290 */ encodeFileToFile( String infile, String outfile )1291 public static boolean encodeFileToFile( String infile, String outfile ) 1292 { 1293 boolean success = false; 1294 java.io.InputStream in = null; 1295 java.io.OutputStream out = null; 1296 try{ 1297 in = new Base64.InputStream( 1298 new java.io.BufferedInputStream( 1299 new java.io.FileInputStream( infile ) ), 1300 Base64.ENCODE ); 1301 out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); 1302 byte[] buffer = new byte[65536]; // 64K 1303 int read = -1; 1304 while( ( read = in.read(buffer) ) >= 0 ){ 1305 out.write( buffer,0,read ); 1306 } // end while: through file 1307 success = true; 1308 } catch( java.io.IOException exc ){ 1309 exc.printStackTrace(); 1310 } finally{ 1311 try{ in.close(); } catch( Exception exc ){} 1312 try{ out.close(); } catch( Exception exc ){} 1313 } // end finally 1314 1315 return success; 1316 } // end encodeFileToFile 1317 1318 1319 1320 /** 1321 * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. 1322 * 1323 * @param infile Input file 1324 * @param outfile Output file 1325 * @return true if the operation is successful 1326 * @since 2.2 1327 */ decodeFileToFile( String infile, String outfile )1328 public static boolean decodeFileToFile( String infile, String outfile ) 1329 { 1330 boolean success = false; 1331 java.io.InputStream in = null; 1332 java.io.OutputStream out = null; 1333 try{ 1334 in = new Base64.InputStream( 1335 new java.io.BufferedInputStream( 1336 new java.io.FileInputStream( infile ) ), 1337 Base64.DECODE ); 1338 out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); 1339 byte[] buffer = new byte[65536]; // 64K 1340 int read = -1; 1341 while( ( read = in.read(buffer) ) >= 0 ){ 1342 out.write( buffer,0,read ); 1343 } // end while: through file 1344 success = true; 1345 } catch( java.io.IOException exc ){ 1346 exc.printStackTrace(); 1347 } finally{ 1348 try{ in.close(); } catch( Exception exc ){} 1349 try{ out.close(); } catch( Exception exc ){} 1350 } // end finally 1351 1352 return success; 1353 } // end decodeFileToFile 1354 1355 1356 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ 1357 1358 1359 1360 /** 1361 * A {@link Base64.InputStream} will read data from another 1362 * <tt>java.io.InputStream</tt>, given in the constructor, 1363 * and encode/decode to/from Base64 notation on the fly. 1364 * 1365 * @see Base64 1366 * @since 1.3 1367 */ 1368 public static class InputStream extends java.io.FilterInputStream 1369 { 1370 private boolean encode; // Encoding or decoding 1371 private int position; // Current position in the buffer 1372 private byte[] buffer; // Small buffer holding converted data 1373 private int bufferLength; // Length of buffer (3 or 4) 1374 private int numSigBytes; // Number of meaningful bytes in the buffer 1375 private int lineLength; 1376 private boolean breakLines; // Break lines at less than 80 characters 1377 private int options; // Record options used to create the stream. 1378 private byte[] alphabet; // Local copies to avoid extra method calls 1379 private byte[] decodabet; // Local copies to avoid extra method calls 1380 1381 1382 /** 1383 * Constructs a {@link Base64.InputStream} in DECODE mode. 1384 * 1385 * @param in the <tt>java.io.InputStream</tt> from which to read data. 1386 * @since 1.3 1387 */ InputStream( java.io.InputStream in )1388 public InputStream( java.io.InputStream in ) 1389 { 1390 this( in, DECODE ); 1391 } // end constructor 1392 1393 1394 /** 1395 * Constructs a {@link Base64.InputStream} in 1396 * either ENCODE or DECODE mode. 1397 * <p> 1398 * Valid options:<pre> 1399 * ENCODE or DECODE: Encode or Decode as data is read. 1400 * DONT_BREAK_LINES: don't break lines at 76 characters 1401 * (only meaningful when encoding) 1402 * <i>Note: Technically, this makes your encoding non-compliant.</i> 1403 * </pre> 1404 * <p> 1405 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> 1406 * 1407 * 1408 * @param in the <tt>java.io.InputStream</tt> from which to read data. 1409 * @param options Specified options 1410 * @see Base64#ENCODE 1411 * @see Base64#DECODE 1412 * @see Base64#DONT_BREAK_LINES 1413 * @since 2.0 1414 */ InputStream( java.io.InputStream in, int options )1415 public InputStream( java.io.InputStream in, int options ) 1416 { 1417 super( in ); 1418 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; 1419 this.encode = (options & ENCODE) == ENCODE; 1420 this.bufferLength = encode ? 4 : 3; 1421 this.buffer = new byte[ bufferLength ]; 1422 this.position = -1; 1423 this.lineLength = 0; 1424 this.options = options; // Record for later, mostly to determine which alphabet to use 1425 this.alphabet = getAlphabet(options); 1426 this.decodabet = getDecodabet(options); 1427 } // end constructor 1428 1429 /** 1430 * Reads enough of the input stream to convert 1431 * to/from Base64 and returns the next byte. 1432 * 1433 * @return next byte 1434 * @since 1.3 1435 */ read()1436 public int read() throws java.io.IOException 1437 { 1438 // Do we need to get data? 1439 if( position < 0 ) 1440 { 1441 if( encode ) 1442 { 1443 byte[] b3 = new byte[3]; 1444 int numBinaryBytes = 0; 1445 for( int i = 0; i < 3; i++ ) 1446 { 1447 try 1448 { 1449 int b = in.read(); 1450 1451 // If end of stream, b is -1. 1452 if( b >= 0 ) 1453 { 1454 b3[i] = (byte)b; 1455 numBinaryBytes++; 1456 } // end if: not end of stream 1457 1458 } // end try: read 1459 catch( java.io.IOException e ) 1460 { 1461 // Only a problem if we got no data at all. 1462 if( i == 0 ) 1463 throw e; 1464 1465 } // end catch 1466 } // end for: each needed input byte 1467 1468 if( numBinaryBytes > 0 ) 1469 { 1470 encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); 1471 position = 0; 1472 numSigBytes = 4; 1473 } // end if: got data 1474 else 1475 { 1476 return -1; 1477 } // end else 1478 } // end if: encoding 1479 1480 // Else decoding 1481 else 1482 { 1483 byte[] b4 = new byte[4]; 1484 int i = 0; 1485 for( i = 0; i < 4; i++ ) 1486 { 1487 // Read four "meaningful" bytes: 1488 int b = 0; 1489 do{ b = in.read(); } 1490 while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); 1491 1492 if( b < 0 ) 1493 break; // Reads a -1 if end of stream 1494 1495 b4[i] = (byte)b; 1496 } // end for: each needed input byte 1497 1498 if( i == 4 ) 1499 { 1500 numSigBytes = decode4to3( b4, 0, buffer, 0, options ); 1501 position = 0; 1502 } // end if: got four characters 1503 else if( i == 0 ){ 1504 return -1; 1505 } // end else if: also padded correctly 1506 else 1507 { 1508 // Must have broken out from above. 1509 throw new java.io.IOException( "Improperly padded Base64 input." ); 1510 } // end 1511 1512 } // end else: decode 1513 } // end else: get data 1514 1515 // Got data? 1516 if( position >= 0 ) 1517 { 1518 // End of relevant data? 1519 if( /*!encode &&*/ position >= numSigBytes ) 1520 return -1; 1521 1522 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) 1523 { 1524 lineLength = 0; 1525 return '\n'; 1526 } // end if 1527 else 1528 { 1529 lineLength++; // This isn't important when decoding 1530 // but throwing an extra "if" seems 1531 // just as wasteful. 1532 1533 int b = buffer[ position++ ]; 1534 1535 if( position >= bufferLength ) 1536 position = -1; 1537 1538 return b & 0xFF; // This is how you "cast" a byte that's 1539 // intended to be unsigned. 1540 } // end else 1541 } // end if: position >= 0 1542 1543 // Else error 1544 else 1545 { 1546 // When JDK1.4 is more accepted, use an assertion here. 1547 throw new java.io.IOException( "Error in Base64 code reading stream." ); 1548 } // end else 1549 } // end read 1550 1551 1552 /** 1553 * Calls {@link #read()} repeatedly until the end of stream 1554 * is reached or <var>len</var> bytes are read. 1555 * Returns number of bytes read into array or -1 if 1556 * end of stream is encountered. 1557 * 1558 * @param dest array to hold values 1559 * @param off offset for array 1560 * @param len max number of bytes to read into array 1561 * @return bytes read into array or -1 if end of stream is encountered. 1562 * @since 1.3 1563 */ read( byte[] dest, int off, int len )1564 public int read( byte[] dest, int off, int len ) throws java.io.IOException 1565 { 1566 int i; 1567 int b; 1568 for( i = 0; i < len; i++ ) 1569 { 1570 b = read(); 1571 1572 //if( b < 0 && i == 0 ) 1573 // return -1; 1574 1575 if( b >= 0 ) 1576 dest[off + i] = (byte)b; 1577 else if( i == 0 ) 1578 return -1; 1579 else 1580 break; // Out of 'for' loop 1581 } // end for: each byte read 1582 return i; 1583 } // end read 1584 1585 } // end inner class InputStream 1586 1587 1588 1589 1590 1591 1592 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ 1593 1594 1595 1596 /** 1597 * A {@link Base64.OutputStream} will write data to another 1598 * <tt>java.io.OutputStream</tt>, given in the constructor, 1599 * and encode/decode to/from Base64 notation on the fly. 1600 * 1601 * @see Base64 1602 * @since 1.3 1603 */ 1604 public static class OutputStream extends java.io.FilterOutputStream 1605 { 1606 private boolean encode; 1607 private int position; 1608 private byte[] buffer; 1609 private int bufferLength; 1610 private int lineLength; 1611 private boolean breakLines; 1612 private byte[] b4; // Scratch used in a few places 1613 private boolean suspendEncoding; 1614 private int options; // Record for later 1615 private byte[] alphabet; // Local copies to avoid extra method calls 1616 private byte[] decodabet; // Local copies to avoid extra method calls 1617 1618 /** 1619 * Constructs a {@link Base64.OutputStream} in ENCODE mode. 1620 * 1621 * @param out the <tt>java.io.OutputStream</tt> to which data will be written. 1622 * @since 1.3 1623 */ OutputStream( java.io.OutputStream out )1624 public OutputStream( java.io.OutputStream out ) 1625 { 1626 this( out, ENCODE ); 1627 } // end constructor 1628 1629 1630 /** 1631 * Constructs a {@link Base64.OutputStream} in 1632 * either ENCODE or DECODE mode. 1633 * <p> 1634 * Valid options:<pre> 1635 * ENCODE or DECODE: Encode or Decode as data is read. 1636 * DONT_BREAK_LINES: don't break lines at 76 characters 1637 * (only meaningful when encoding) 1638 * <i>Note: Technically, this makes your encoding non-compliant.</i> 1639 * </pre> 1640 * <p> 1641 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> 1642 * 1643 * @param out the <tt>java.io.OutputStream</tt> to which data will be written. 1644 * @param options Specified options. 1645 * @see Base64#ENCODE 1646 * @see Base64#DECODE 1647 * @see Base64#DONT_BREAK_LINES 1648 * @since 1.3 1649 */ OutputStream( java.io.OutputStream out, int options )1650 public OutputStream( java.io.OutputStream out, int options ) 1651 { 1652 super( out ); 1653 this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; 1654 this.encode = (options & ENCODE) == ENCODE; 1655 this.bufferLength = encode ? 3 : 4; 1656 this.buffer = new byte[ bufferLength ]; 1657 this.position = 0; 1658 this.lineLength = 0; 1659 this.suspendEncoding = false; 1660 this.b4 = new byte[4]; 1661 this.options = options; 1662 this.alphabet = getAlphabet(options); 1663 this.decodabet = getDecodabet(options); 1664 } // end constructor 1665 1666 1667 /** 1668 * Writes the byte to the output stream after 1669 * converting to/from Base64 notation. 1670 * When encoding, bytes are buffered three 1671 * at a time before the output stream actually 1672 * gets a write() call. 1673 * When decoding, bytes are buffered four 1674 * at a time. 1675 * 1676 * @param theByte the byte to write 1677 * @since 1.3 1678 */ write(int theByte)1679 public void write(int theByte) throws java.io.IOException 1680 { 1681 // Encoding suspended? 1682 if( suspendEncoding ) 1683 { 1684 super.out.write( theByte ); 1685 return; 1686 } // end if: supsended 1687 1688 // Encode? 1689 if( encode ) 1690 { 1691 buffer[ position++ ] = (byte)theByte; 1692 if( position >= bufferLength ) // Enough to encode. 1693 { 1694 out.write( encode3to4( b4, buffer, bufferLength, options ) ); 1695 1696 lineLength += 4; 1697 if( breakLines && lineLength >= MAX_LINE_LENGTH ) 1698 { 1699 out.write( NEW_LINE ); 1700 lineLength = 0; 1701 } // end if: end of line 1702 1703 position = 0; 1704 } // end if: enough to output 1705 } // end if: encoding 1706 1707 // Else, Decoding 1708 else 1709 { 1710 // Meaningful Base64 character? 1711 if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) 1712 { 1713 buffer[ position++ ] = (byte)theByte; 1714 if( position >= bufferLength ) // Enough to output. 1715 { 1716 int len = Base64.decode4to3( buffer, 0, b4, 0, options ); 1717 out.write( b4, 0, len ); 1718 //out.write( Base64.decode4to3( buffer ) ); 1719 position = 0; 1720 } // end if: enough to output 1721 } // end if: meaningful base64 character 1722 else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) 1723 { 1724 throw new java.io.IOException( "Invalid character in Base64 data." ); 1725 } // end else: not white space either 1726 } // end else: decoding 1727 } // end write 1728 1729 1730 1731 /** 1732 * Calls {@link #write(int)} repeatedly until <var>len</var> 1733 * bytes are written. 1734 * 1735 * @param theBytes array from which to read bytes 1736 * @param off offset for array 1737 * @param len max number of bytes to read into array 1738 * @since 1.3 1739 */ write( byte[] theBytes, int off, int len )1740 public void write( byte[] theBytes, int off, int len ) throws java.io.IOException 1741 { 1742 // Encoding suspended? 1743 if( suspendEncoding ) 1744 { 1745 super.out.write( theBytes, off, len ); 1746 return; 1747 } // end if: supsended 1748 1749 for( int i = 0; i < len; i++ ) 1750 { 1751 write( theBytes[ off + i ] ); 1752 } // end for: each byte written 1753 1754 } // end write 1755 1756 1757 1758 /** 1759 * Method added by PHIL. [Thanks, PHIL. -Rob] 1760 * This pads the buffer without closing the stream. 1761 */ flushBase64()1762 public void flushBase64() throws java.io.IOException 1763 { 1764 if( position > 0 ) 1765 { 1766 if( encode ) 1767 { 1768 out.write( encode3to4( b4, buffer, position, options ) ); 1769 position = 0; 1770 } // end if: encoding 1771 else 1772 { 1773 throw new java.io.IOException( "Base64 input not properly padded." ); 1774 } // end else: decoding 1775 } // end if: buffer partially full 1776 1777 } // end flush 1778 1779 1780 /** 1781 * Flushes and closes (I think, in the superclass) the stream. 1782 * 1783 * @since 1.3 1784 */ close()1785 public void close() throws java.io.IOException 1786 { 1787 // 1. Ensure that pending characters are written 1788 flushBase64(); 1789 1790 // 2. Actually close the stream 1791 // Base class both flushes and closes. 1792 super.close(); 1793 1794 buffer = null; 1795 out = null; 1796 } // end close 1797 1798 1799 1800 /** 1801 * Suspends encoding of the stream. 1802 * May be helpful if you need to embed a piece of 1803 * base640-encoded data in a stream. 1804 * 1805 * @since 1.5.1 1806 */ suspendEncoding()1807 public void suspendEncoding() throws java.io.IOException 1808 { 1809 flushBase64(); 1810 this.suspendEncoding = true; 1811 } // end suspendEncoding 1812 1813 1814 /** 1815 * Resumes encoding of the stream. 1816 * May be helpful if you need to embed a piece of 1817 * base640-encoded data in a stream. 1818 * 1819 * @since 1.5.1 1820 */ resumeEncoding()1821 public void resumeEncoding() 1822 { 1823 this.suspendEncoding = false; 1824 } // end resumeEncoding 1825 1826 1827 1828 } // end inner class OutputStream 1829 1830 1831 } // end class Base64 1832