001package com.randomnoun.common; 002 003/* (c) 2013 randomnoun. All Rights Reserved. This work is licensed under a 004 * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html) 005 */ 006 007// this class was taken from the widen valet (aws route53) package 008 009/** 010 * <p>Encodes and decodes to and from Base64 notation.</p> 011 * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> 012 * 013 * <p>Example:</p> 014 * 015 * <p><code>String encoded = Base64.encode( myByteArray );</code></p> 016 * 017 * <p><code>byte[] myByteArray = Base64.decode( encoded );</code></p> 018 * 019 * <p>The <code>options</code> parameter, which appears in a few places, is used to pass 020 * several pieces of information to the encoder. In the "higher level" methods such as 021 * encodeBytes( bytes, options ) the options parameter can be used to indicate such 022 * things as first gzipping the bytes before encoding them, not inserting linefeeds, 023 * and encoding using the URL-safe and Ordered dialects.</p> 024 * 025 * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, 026 * Section 2.1, implementations should not add line feeds unless explicitly told 027 * to do so. I've got Base64 set to this behavior now, although earlier versions 028 * broke lines by default.</p> 029 * 030 * <p>The constants defined in Base64 can be OR-ed together to combine options, so you 031 * might make a call like this:</p> 032 * 033 * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code> 034 * <p>to compress the data before encoding it and then making the output have newline characters.</p> 035 * <p>Also...</p> 036 * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code> 037 * 038 * 039 * 040 * <p> 041 * Change Log: 042 * </p> 043 * <ul> 044 * <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the 045 * value 01111111, which is an invalid base 64 character but should not 046 * throw an ArrayIndexOutOfBoundsException either. Led to discovery of 047 * mishandling (or potential for better handling) of other bad input 048 * characters. You should now get an IOException if you try decoding 049 * something that has bad characters in it.</li> 050 * <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded 051 * string ended in the last column; the buffer was not properly shrunk and 052 * contained an extra (null) byte that made it into the string.</li> 053 * <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size 054 * was wrong for files of size 31, 34, and 37 bytes.</li> 055 * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing 056 * the Base64.OutputStream closed the Base64 encoding (by padding with equals 057 * signs) too soon. Also added an option to suppress the automatic decoding 058 * of gzipped streams. Also added experimental support for specifying a 059 * class loader when using the 060 * {@link #decodeToObject(String, int, ClassLoader)} 061 * method.</li> 062 * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java 063 * footprint with its CharEncoders and so forth. Fixed some javadocs that were 064 * inconsistent. Removed imports and specified things like java.io.IOException 065 * explicitly inline.</li> 066 * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the 067 * final encoded data will be so that the code doesn't have to create two output 068 * arrays: an oversized initial one and then a final, exact-sized one. Big win 069 * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not 070 * using the gzip options which uses a different mechanism with streams and stuff).</li> 071 * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some 072 * similar helper methods to be more efficient with memory by not returning a 073 * String but just a byte array.</li> 074 * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments 075 * and bug fixes queued up and finally executed. Thanks to everyone who sent 076 * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. 077 * Much bad coding was cleaned up including throwing exceptions where necessary 078 * instead of returning null values or something similar. Here are some changes 079 * that may affect you: 080 * <ul> 081 * <li><em>Does not break lines, by default.</em> This is to keep in compliance with 082 * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li> 083 * <li><em>Throws exceptions instead of returning null values.</em> Because some operations 084 * (especially those that may permit the GZIP option) use IO streams, there 085 * is a possiblity of an java.io.IOException being thrown. After some discussion and 086 * thought, I've changed the behavior of the methods to throw java.io.IOExceptions 087 * rather than return null if ever there's an error. I think this is more 088 * appropriate, though it will require some changes to your code. Sorry, 089 * it should have been done this way to begin with.</li> 090 * <li><em>Removed all references to System.out, System.err, and the like.</em> 091 * Shame on me. All I can say is sorry they were ever there.</li> 092 * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed 093 * such as when passed arrays are null or offsets are invalid.</li> 094 * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings. 095 * This was especially annoying before for people who were thorough in their 096 * own projects and then had gobs of javadoc warnings on this file.</li> 097 * </ul> 098 * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug 099 * when using very small files (~< 40 bytes).</li> 100 * <li>v2.2 - Added some helper methods for encoding/decoding directly from 101 * one file to the next. Also added a main() method to support command line 102 * encoding/decoding from one file to the next. Also added these Base64 dialects: 103 * <ol> 104 * <li>The default is RFC3548 format.</li> 105 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates 106 * URL and file name friendly format as described in Section 4 of RFC3548. 107 * http://www.faqs.org/rfcs/rfc3548.html</li> 108 * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates 109 * URL and file name friendly format that preserves lexical ordering as described 110 * in http://www.faqs.org/qa/rfcc-1940.html</li> 111 * </ol> 112 * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> 113 * for contributing the new Base64 dialects. 114 * </li> 115 * 116 * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added 117 * some convenience methods for reading and writing to and from files.</li> 118 * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems 119 * with other encodings (like EBCDIC).</li> 120 * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the 121 * encoded data was a single byte.</li> 122 * <li>v2.0 - I got rid of methods that used booleans to set options. 123 * Now everything is more consolidated and cleaner. The code now detects 124 * when data that's being decoded is gzip-compressed and will decompress it 125 * automatically. Generally things are cleaner. You'll probably have to 126 * change some method calls that you were making to support the new 127 * options format (<code>int</code>s that you "OR" together).</li> 128 * <li>v1.5.1 - Fixed bug when decompressing and decoding to a 129 * byte[] using <code>decode( String s, boolean gzipCompressed )</code>. 130 * Added the ability to "suspend" encoding in the Output Stream so 131 * you can turn on and off the encoding if you need to embed base64 132 * data in an otherwise "normal" stream (like an XML file).</li> 133 * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. 134 * This helps when using GZIP streams. 135 * Added the ability to GZip-compress objects before encoding them.</li> 136 * <li>v1.4 - Added helper methods to read/write files.</li> 137 * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> 138 * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream 139 * where last buffer being read, if not completely full, was not returned.</li> 140 * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> 141 * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> 142 * </ul> 143 * 144 * <p> 145 * I am placing this code in the Public Domain. Do with it as you will. 146 * This software comes with no guarantees or warranties but with 147 * plenty of well-wishing instead! 148 * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> 149 * periodically to check for updates or to contribute improvements. 150 * </p> 151 * 152 * @author Robert Harder 153 * @author rob@iharder.net 154 * @version 2.3.7 155 */ 156public class Base64 157{ 158 159 160 161 162/* ******** P U B L I C F I E L D S ******** */ 163 164 165 /** No options specified. Value is zero. */ 166 public final static int NO_OPTIONS = 0; 167 168 /** Specify encoding in first bit. Value is one. */ 169 public final static int ENCODE = 1; 170 171 172 /** Specify decoding in first bit. Value is zero. */ 173 public final static int DECODE = 0; 174 175 176 /** Specify that data should be gzip-compressed in second bit. Value is two. */ 177 public final static int GZIP = 2; 178 179 /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */ 180 public final static int DONT_GUNZIP = 4; 181 182 183 /** Do break lines when encoding. Value is 8. */ 184 public final static int DO_BREAK_LINES = 8; 185 186 /** 187 * Encode using Base64-like encoding that is URL- and Filename-safe as described 188 * in Section 4 of RFC3548: 189 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. 190 * It is important to note that data encoded this way is <em>not</em> officially valid Base64, 191 * or at the very least should not be called Base64 without also specifying that is 192 * was encoded using the URL- and Filename-safe dialect. 193 */ 194 public final static int URL_SAFE = 16; 195 196 197 /** 198 * Encode using the special "ordered" dialect of Base64 described here: 199 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. 200 */ 201 public final static int ORDERED = 32; 202 203 204/* ******** P R I V A T E F I E L D S ******** */ 205 206 207 /** Maximum line length (76) of Base64 output. */ 208 private final static int MAX_LINE_LENGTH = 76; 209 210 211 /** The equals sign (=) as a byte. */ 212 private final static byte EQUALS_SIGN = (byte)'='; 213 214 215 /** The new line character (\n) as a byte. */ 216 private final static byte NEW_LINE = (byte)'\n'; 217 218 219 /** Preferred encoding. */ 220 private final static String PREFERRED_ENCODING = "US-ASCII"; 221 222 223 private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding 224 private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding 225 226 227/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ 228 229 /** The 64 valid Base64 values. */ 230 /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ 231 private final static byte[] _STANDARD_ALPHABET = { 232 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 233 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 234 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 235 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 236 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 237 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 238 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 239 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', 240 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 241 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' 242 }; 243 244 245 /** 246 * Translates a Base64 value to either its 6-bit reconstruction value 247 * or a negative number indicating some other meaning. 248 **/ 249 private final static byte[] _STANDARD_DECODABET = { 250 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 251 -5,-5, // Whitespace: Tab and Linefeed 252 -9,-9, // Decimal 11 - 12 253 -5, // Whitespace: Carriage Return 254 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 255 -9,-9,-9,-9,-9, // Decimal 27 - 31 256 -5, // Whitespace: Space 257 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 258 62, // Plus sign at decimal 43 259 -9,-9,-9, // Decimal 44 - 46 260 63, // Slash at decimal 47 261 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine 262 -9,-9,-9, // Decimal 58 - 60 263 -1, // Equals sign at decimal 61 264 -9,-9,-9, // Decimal 62 - 64 265 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 266 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' 267 -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 268 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 269 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' 270 -9,-9,-9,-9,-9 // Decimal 123 - 127 271 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 272 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 273 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 274 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 275 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 276 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 277 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 278 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 279 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 280 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 281 }; 282 283 284/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ 285 286 /** 287 * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: 288 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. 289 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." 290 */ 291 private final static byte[] _URL_SAFE_ALPHABET = { 292 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 293 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 294 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 295 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 296 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 297 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 298 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 299 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', 300 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 301 (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' 302 }; 303 304 /** 305 * Used in decoding URL- and Filename-safe dialects of Base64. 306 */ 307 private final static byte[] _URL_SAFE_DECODABET = { 308 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 309 -5,-5, // Whitespace: Tab and Linefeed 310 -9,-9, // Decimal 11 - 12 311 -5, // Whitespace: Carriage Return 312 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 313 -9,-9,-9,-9,-9, // Decimal 27 - 31 314 -5, // Whitespace: Space 315 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 316 -9, // Plus sign at decimal 43 317 -9, // Decimal 44 318 62, // Minus sign at decimal 45 319 -9, // Decimal 46 320 -9, // Slash at decimal 47 321 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine 322 -9,-9,-9, // Decimal 58 - 60 323 -1, // Equals sign at decimal 61 324 -9,-9,-9, // Decimal 62 - 64 325 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 326 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' 327 -9,-9,-9,-9, // Decimal 91 - 94 328 63, // Underscore at decimal 95 329 -9, // Decimal 96 330 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 331 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' 332 -9,-9,-9,-9,-9 // Decimal 123 - 127 333 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 334 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 335 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 336 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 337 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 338 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 339 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 340 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 341 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 342 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 343 }; 344 345 346 347/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ 348 349 /** 350 * I don't get the point of this technique, but someone requested it, 351 * and it is described here: 352 * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. 353 */ 354 private final static byte[] _ORDERED_ALPHABET = { 355 (byte)'-', 356 (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', 357 (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', 358 (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 359 (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 360 (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 361 (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 362 (byte)'_', 363 (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 364 (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 365 (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 366 (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' 367 }; 368 369 /** 370 * Used in decoding the "ordered" dialect of Base64. 371 */ 372 private final static byte[] _ORDERED_DECODABET = { 373 -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 374 -5,-5, // Whitespace: Tab and Linefeed 375 -9,-9, // Decimal 11 - 12 376 -5, // Whitespace: Carriage Return 377 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 378 -9,-9,-9,-9,-9, // Decimal 27 - 31 379 -5, // Whitespace: Space 380 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 381 -9, // Plus sign at decimal 43 382 -9, // Decimal 44 383 0, // Minus sign at decimal 45 384 -9, // Decimal 46 385 -9, // Slash at decimal 47 386 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine 387 -9,-9,-9, // Decimal 58 - 60 388 -1, // Equals sign at decimal 61 389 -9,-9,-9, // Decimal 62 - 64 390 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 391 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' 392 -9,-9,-9,-9, // Decimal 91 - 94 393 37, // Underscore at decimal 95 394 -9, // Decimal 96 395 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 396 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' 397 -9,-9,-9,-9,-9 // Decimal 123 - 127 398 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 399 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 400 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 401 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 402 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 403 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 404 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 405 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 406 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 407 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 408 }; 409 410 411/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ 412 413 414 /** 415 * Returns one of the _SOMETHING_ALPHABET byte arrays depending on 416 * the options specified. 417 * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE 418 * in which case one of them will be picked, though there is 419 * no guarantee as to which one will be picked. 420 */ 421 private final static byte[] getAlphabet( int options ) { 422 if ((options & URL_SAFE) == URL_SAFE) { 423 return _URL_SAFE_ALPHABET; 424 } else if ((options & ORDERED) == ORDERED) { 425 return _ORDERED_ALPHABET; 426 } else { 427 return _STANDARD_ALPHABET; 428 } 429 } // end getAlphabet 430 431 432 /** 433 * Returns one of the _SOMETHING_DECODABET byte arrays depending on 434 * the options specified. 435 * It's possible, though silly, to specify ORDERED and URL_SAFE 436 * in which case one of them will be picked, though there is 437 * no guarantee as to which one will be picked. 438 */ 439 private final static byte[] getDecodabet( int options ) { 440 if( (options & URL_SAFE) == URL_SAFE) { 441 return _URL_SAFE_DECODABET; 442 } else if ((options & ORDERED) == ORDERED) { 443 return _ORDERED_DECODABET; 444 } else { 445 return _STANDARD_DECODABET; 446 } 447 } // end getAlphabet 448 449 450 451 /** Defeats instantiation. */ 452 private Base64(){} 453 454 455 456 457/* ******** E N C O D I N G M E T H O D S ******** */ 458 459 460 /** 461 * Encodes up to the first three bytes of array <var>threeBytes</var> 462 * and returns a four-byte array in Base64 notation. 463 * The actual number of significant bytes in your array is 464 * given by <var>numSigBytes</var>. 465 * The array <var>threeBytes</var> needs only be as big as 466 * <var>numSigBytes</var>. 467 * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. 468 * 469 * @param b4 A reusable byte array to reduce array instantiation 470 * @param threeBytes the array to convert 471 * @param numSigBytes the number of significant bytes in your array 472 * @return four byte array in Base64 notation. 473 * @since 1.5.1 474 */ 475 private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { 476 encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); 477 return b4; 478 } // end encode3to4 479 480 481 /** 482 * <p>Encodes up to three bytes of the array <var>source</var> 483 * and writes the resulting four Base64 bytes to <var>destination</var>. 484 * The source and destination arrays can be manipulated 485 * anywhere along their length by specifying 486 * <var>srcOffset</var> and <var>destOffset</var>. 487 * This method does not check to make sure your arrays 488 * are large enough to accomodate <var>srcOffset</var> + 3 for 489 * the <var>source</var> array or <var>destOffset</var> + 4 for 490 * the <var>destination</var> array. 491 * The actual number of significant bytes in your array is 492 * given by <var>numSigBytes</var>.</p> 493 * <p>This is the lowest level of the encoding methods with 494 * all possible parameters.</p> 495 * 496 * @param source the array to convert 497 * @param srcOffset the index where conversion begins 498 * @param numSigBytes the number of significant bytes in your array 499 * @param destination the array to hold the conversion 500 * @param destOffset the index where output will be put 501 * @return the <var>destination</var> array 502 * @since 1.3 503 */ 504 private static byte[] encode3to4( 505 byte[] source, int srcOffset, int numSigBytes, 506 byte[] destination, int destOffset, int options ) { 507 508 byte[] ALPHABET = getAlphabet( options ); 509 510 // 1 2 3 511 // 01234567890123456789012345678901 Bit position 512 // --------000000001111111122222222 Array position from threeBytes 513 // --------| || || || | Six bit groups to index ALPHABET 514 // >>18 >>12 >> 6 >> 0 Right shift necessary 515 // 0x3f 0x3f 0x3f Additional AND 516 517 // Create buffer with zero-padding if there are only one or two 518 // significant bytes passed in the array. 519 // We have to shift left 24 in order to flush out the 1's that appear 520 // when Java treats a value as negative that is cast from a byte to an int. 521 int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) 522 | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) 523 | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); 524 525 switch( numSigBytes ) 526 { 527 case 3: 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 ] = ALPHABET[ (inBuff ) & 0x3f ]; 532 return destination; 533 534 case 2: 535 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 536 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 537 destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; 538 destination[ destOffset + 3 ] = EQUALS_SIGN; 539 return destination; 540 541 case 1: 542 destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 543 destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 544 destination[ destOffset + 2 ] = EQUALS_SIGN; 545 destination[ destOffset + 3 ] = EQUALS_SIGN; 546 return destination; 547 548 default: 549 return destination; 550 } // end switch 551 } // end encode3to4 552 553 554 555 /** 556 * Performs Base64 encoding on the <code>raw</code> ByteBuffer, 557 * writing it to the <code>encoded</code> ByteBuffer. 558 * This is an experimental feature. Currently it does not 559 * pass along any options (such as {@link #DO_BREAK_LINES} 560 * or {@link #GZIP}. 561 * 562 * @param raw input buffer 563 * @param encoded output buffer 564 * @since 2.3 565 */ 566 public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ 567 byte[] raw3 = new byte[3]; 568 byte[] enc4 = new byte[4]; 569 570 while( raw.hasRemaining() ){ 571 int rem = Math.min(3,raw.remaining()); 572 raw.get(raw3,0,rem); 573 Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); 574 encoded.put(enc4); 575 } // end input remaining 576 } 577 578 579 /** 580 * Performs Base64 encoding on the <code>raw</code> ByteBuffer, 581 * writing it to the <code>encoded</code> CharBuffer. 582 * This is an experimental feature. Currently it does not 583 * pass along any options (such as {@link #DO_BREAK_LINES} 584 * or {@link #GZIP}. 585 * 586 * @param raw input buffer 587 * @param encoded output buffer 588 * @since 2.3 589 */ 590 public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ 591 byte[] raw3 = new byte[3]; 592 byte[] enc4 = new byte[4]; 593 594 while( raw.hasRemaining() ){ 595 int rem = Math.min(3,raw.remaining()); 596 raw.get(raw3,0,rem); 597 Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); 598 for( int i = 0; i < 4; i++ ){ 599 encoded.put( (char)(enc4[i] & 0xFF) ); 600 } 601 } // end input remaining 602 } 603 604 605 606 607 /** 608 * Serializes an object and returns the Base64-encoded 609 * version of that serialized object. 610 * 611 * <p>As of v 2.3, if the object 612 * cannot be serialized or there is another error, 613 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 614 * In earlier versions, it just returned a null value, but 615 * in retrospect that's a pretty poor way to handle it.</p> 616 * 617 * The object is not GZip-compressed before being encoded. 618 * 619 * @param serializableObject The object to encode 620 * @return The Base64-encoded object 621 * @throws java.io.IOException if there is an error 622 * @throws NullPointerException if serializedObject is null 623 * @since 1.4 624 */ 625 public static String encodeObject( java.io.Serializable serializableObject ) 626 throws java.io.IOException { 627 return encodeObject( serializableObject, NO_OPTIONS ); 628 } // end encodeObject 629 630 631 632 /** 633 * Serializes an object and returns the Base64-encoded 634 * version of that serialized object. 635 * 636 * <p>As of v 2.3, if the object 637 * cannot be serialized or there is another error, 638 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 639 * In earlier versions, it just returned a null value, but 640 * in retrospect that's a pretty poor way to handle it.</p> 641 * 642 * The object is not GZip-compressed before being encoded. 643 * <p> 644 * Example options:<pre> 645 * GZIP: gzip-compresses object before encoding it. 646 * DO_BREAK_LINES: break lines at 76 characters 647 * </pre> 648 * <p> 649 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or 650 * <p> 651 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code> 652 * 653 * @param serializableObject The object to encode 654 * @param options Specified options 655 * @return The Base64-encoded object 656 * @see Base64#GZIP 657 * @see Base64#DO_BREAK_LINES 658 * @throws java.io.IOException if there is an error 659 * @since 2.0 660 */ 661 public static String encodeObject( java.io.Serializable serializableObject, int options ) 662 throws java.io.IOException { 663 664 if( serializableObject == null ){ 665 throw new NullPointerException( "Cannot serialize a null object." ); 666 } // end if: null 667 668 // Streams 669 java.io.ByteArrayOutputStream baos = null; 670 java.io.OutputStream b64os = null; 671 java.util.zip.GZIPOutputStream gzos = null; 672 java.io.ObjectOutputStream oos = null; 673 674 675 try { 676 // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream 677 baos = new java.io.ByteArrayOutputStream(); 678 b64os = new OutputStream( baos, ENCODE | options ); 679 if( (options & GZIP) != 0 ){ 680 // Gzip 681 gzos = new java.util.zip.GZIPOutputStream(b64os); 682 oos = new java.io.ObjectOutputStream( gzos ); 683 } else { 684 // Not gzipped 685 oos = new java.io.ObjectOutputStream( b64os ); 686 } 687 oos.writeObject( serializableObject ); 688 } // end try 689 catch( java.io.IOException e ) { 690 // Catch it and then throw it immediately so that 691 // the finally{} block is called for cleanup. 692 throw e; 693 } // end catch 694 finally { 695 try{ oos.close(); } catch( Exception e ){} 696 try{ gzos.close(); } catch( Exception e ){} 697 try{ b64os.close(); } catch( Exception e ){} 698 try{ baos.close(); } catch( Exception e ){} 699 } // end finally 700 701 // Return value according to relevant encoding. 702 try { 703 return new String( baos.toByteArray(), PREFERRED_ENCODING ); 704 } // end try 705 catch (java.io.UnsupportedEncodingException uue){ 706 // Fall back to some Java default 707 return new String( baos.toByteArray() ); 708 } // end catch 709 710 } // end encode 711 712 713 714 /** 715 * Encodes a byte array into Base64 notation. 716 * Does not GZip-compress data. 717 * 718 * @param source The data to convert 719 * @return The data in Base64-encoded form 720 * @throws NullPointerException if source array is null 721 * @since 1.4 722 */ 723 public static String encodeBytes( byte[] source ) { 724 // Since we're not going to have the GZIP encoding turned on, 725 // we're not going to have an java.io.IOException thrown, so 726 // we should not force the user to have to catch it. 727 String encoded = null; 728 try { 729 encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); 730 } catch (java.io.IOException ex) { 731 assert false : ex.getMessage(); 732 } // end catch 733 assert encoded != null; 734 return encoded; 735 } // end encodeBytes 736 737 738 739 /** 740 * Encodes a byte array into Base64 notation. 741 * <p> 742 * Example options:<pre> 743 * GZIP: gzip-compresses object before encoding it. 744 * DO_BREAK_LINES: break lines at 76 characters 745 * <i>Note: Technically, this makes your encoding non-compliant.</i> 746 * </pre> 747 * <p> 748 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or 749 * <p> 750 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> 751 * 752 * 753 * <p>As of v 2.3, if there is an error with the GZIP stream, 754 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 755 * In earlier versions, it just returned a null value, but 756 * in retrospect that's a pretty poor way to handle it.</p> 757 * 758 * 759 * @param source The data to convert 760 * @param options Specified options 761 * @return The Base64-encoded data as a String 762 * @see Base64#GZIP 763 * @see Base64#DO_BREAK_LINES 764 * @throws java.io.IOException if there is an error 765 * @throws NullPointerException if source array is null 766 * @since 2.0 767 */ 768 public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { 769 return encodeBytes( source, 0, source.length, options ); 770 } // end encodeBytes 771 772 773 /** 774 * Encodes a byte array into Base64 notation. 775 * Does not GZip-compress data. 776 * 777 * <p>As of v 2.3, if there is an error, 778 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 779 * In earlier versions, it just returned a null value, but 780 * in retrospect that's a pretty poor way to handle it.</p> 781 * 782 * 783 * @param source The data to convert 784 * @param off Offset in array where conversion should begin 785 * @param len Length of data to convert 786 * @return The Base64-encoded data as a String 787 * @throws NullPointerException if source array is null 788 * @throws IllegalArgumentException if source array, offset, or length are invalid 789 * @since 1.4 790 */ 791 public static String encodeBytes( byte[] source, int off, int len ) { 792 // Since we're not going to have the GZIP encoding turned on, 793 // we're not going to have an java.io.IOException thrown, so 794 // we should not force the user to have to catch it. 795 String encoded = null; 796 try { 797 encoded = encodeBytes( source, off, len, NO_OPTIONS ); 798 } catch (java.io.IOException ex) { 799 assert false : ex.getMessage(); 800 } // end catch 801 assert encoded != null; 802 return encoded; 803 } // end encodeBytes 804 805 806 807 /** 808 * Encodes a byte array into Base64 notation. 809 * <p> 810 * Example options:<pre> 811 * GZIP: gzip-compresses object before encoding it. 812 * DO_BREAK_LINES: break lines at 76 characters 813 * <i>Note: Technically, this makes your encoding non-compliant.</i> 814 * </pre> 815 * <p> 816 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or 817 * <p> 818 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> 819 * 820 * 821 * <p>As of v 2.3, if there is an error with the GZIP stream, 822 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 823 * In earlier versions, it just returned a null value, but 824 * in retrospect that's a pretty poor way to handle it.</p> 825 * 826 * 827 * @param source The data to convert 828 * @param off Offset in array where conversion should begin 829 * @param len Length of data to convert 830 * @param options Specified options 831 * @return The Base64-encoded data as a String 832 * @see Base64#GZIP 833 * @see Base64#DO_BREAK_LINES 834 * @throws java.io.IOException if there is an error 835 * @throws NullPointerException if source array is null 836 * @throws IllegalArgumentException if source array, offset, or length are invalid 837 * @since 2.0 838 */ 839 public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { 840 byte[] encoded = encodeBytesToBytes( source, off, len, options ); 841 842 // Return value according to relevant encoding. 843 try { 844 return new String( encoded, PREFERRED_ENCODING ); 845 } // end try 846 catch (java.io.UnsupportedEncodingException uue) { 847 return new String( encoded ); 848 } // end catch 849 850 } // end encodeBytes 851 852 853 854 855 /** 856 * Similar to {@link #encodeBytes(byte[])} but returns 857 * a byte array instead of instantiating a String. This is more efficient 858 * if you're working with I/O streams and have large data sets to encode. 859 * 860 * 861 * @param source The data to convert 862 * @return The Base64-encoded data as a byte[] (of ASCII characters) 863 * @throws NullPointerException if source array is null 864 * @since 2.3.1 865 */ 866 public static byte[] encodeBytesToBytes( byte[] source ) { 867 byte[] encoded = null; 868 try { 869 encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); 870 } catch( java.io.IOException ex ) { 871 assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); 872 } 873 return encoded; 874 } 875 876 877 /** 878 * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns 879 * a byte array instead of instantiating a String. This is more efficient 880 * if you're working with I/O streams and have large data sets to encode. 881 * 882 * 883 * @param source The data to convert 884 * @param off Offset in array where conversion should begin 885 * @param len Length of data to convert 886 * @param options Specified options 887 * @return The Base64-encoded data as a String 888 * @see Base64#GZIP 889 * @see Base64#DO_BREAK_LINES 890 * @throws java.io.IOException if there is an error 891 * @throws NullPointerException if source array is null 892 * @throws IllegalArgumentException if source array, offset, or length are invalid 893 * @since 2.3.1 894 */ 895 public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { 896 897 if( source == null ){ 898 throw new NullPointerException( "Cannot serialize a null array." ); 899 } // end if: null 900 901 if( off < 0 ){ 902 throw new IllegalArgumentException( "Cannot have negative offset: " + off ); 903 } // end if: off < 0 904 905 if( len < 0 ){ 906 throw new IllegalArgumentException( "Cannot have length offset: " + len ); 907 } // end if: len < 0 908 909 if( off + len > source.length ){ 910 throw new IllegalArgumentException( 911 String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); 912 } // end if: off < 0 913 914 915 916 // Compress? 917 if( (options & GZIP) != 0 ) { 918 java.io.ByteArrayOutputStream baos = null; 919 java.util.zip.GZIPOutputStream gzos = null; 920 OutputStream b64os = null; 921 922 try { 923 // GZip -> Base64 -> ByteArray 924 baos = new java.io.ByteArrayOutputStream(); 925 b64os = new OutputStream( baos, ENCODE | options ); 926 gzos = new java.util.zip.GZIPOutputStream( b64os ); 927 928 gzos.write( source, off, len ); 929 gzos.close(); 930 } // end try 931 catch( java.io.IOException e ) { 932 // Catch it and then throw it immediately so that 933 // the finally{} block is called for cleanup. 934 throw e; 935 } // end catch 936 finally { 937 try{ gzos.close(); } catch( Exception e ){} 938 try{ b64os.close(); } catch( Exception e ){} 939 try{ baos.close(); } catch( Exception e ){} 940 } // end finally 941 942 return baos.toByteArray(); 943 } // end if: compress 944 945 // Else, don't compress. Better not to use streams at all then. 946 else { 947 boolean breakLines = (options & DO_BREAK_LINES) != 0; 948 949 //int len43 = len * 4 / 3; 950 //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 951 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding 952 // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines 953 // Try to determine more precisely how big the array needs to be. 954 // If we get it right, we don't have to do an array copy, and 955 // we save a bunch of memory. 956 int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding 957 if( breakLines ){ 958 encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters 959 } 960 byte[] outBuff = new byte[ encLen ]; 961 962 963 int d = 0; 964 int e = 0; 965 int len2 = len - 2; 966 int lineLength = 0; 967 for( ; d < len2; d+=3, e+=4 ) { 968 encode3to4( source, d+off, 3, outBuff, e, options ); 969 970 lineLength += 4; 971 if( breakLines && lineLength >= MAX_LINE_LENGTH ) 972 { 973 outBuff[e+4] = NEW_LINE; 974 e++; 975 lineLength = 0; 976 } // end if: end of line 977 } // en dfor: each piece of array 978 979 if( d < len ) { 980 encode3to4( source, d+off, len - d, outBuff, e, options ); 981 e += 4; 982 } // end if: some padding needed 983 984 985 // Only resize array if we didn't guess it right. 986 if( e <= outBuff.length - 1 ){ 987 // If breaking lines and the last byte falls right at 988 // the line length (76 bytes per line), there will be 989 // one extra byte, and the array will need to be resized. 990 // Not too bad of an estimate on array size, I'd say. 991 byte[] finalOut = new byte[e]; 992 System.arraycopy(outBuff,0, finalOut,0,e); 993 //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); 994 return finalOut; 995 } else { 996 //System.err.println("No need to resize array."); 997 return outBuff; 998 } 999 1000 } // end else: don't compress 1001 1002 } // end encodeBytesToBytes 1003 1004 1005 1006 1007 1008/* ******** D E C O D I N G M E T H O D S ******** */ 1009 1010 1011 /** 1012 * Decodes four bytes from array <var>source</var> 1013 * and writes the resulting bytes (up to three of them) 1014 * to <var>destination</var>. 1015 * The source and destination arrays can be manipulated 1016 * anywhere along their length by specifying 1017 * <var>srcOffset</var> and <var>destOffset</var>. 1018 * This method does not check to make sure your arrays 1019 * are large enough to accomodate <var>srcOffset</var> + 4 for 1020 * the <var>source</var> array or <var>destOffset</var> + 3 for 1021 * the <var>destination</var> array. 1022 * This method returns the actual number of bytes that 1023 * were converted from the Base64 encoding. 1024 * <p>This is the lowest level of the decoding methods with 1025 * all possible parameters.</p> 1026 * 1027 * 1028 * @param source the array to convert 1029 * @param srcOffset the index where conversion begins 1030 * @param destination the array to hold the conversion 1031 * @param destOffset the index where output will be put 1032 * @param options alphabet type is pulled from this (standard, url-safe, ordered) 1033 * @return the number of decoded bytes converted 1034 * @throws NullPointerException if source or destination arrays are null 1035 * @throws IllegalArgumentException if srcOffset or destOffset are invalid 1036 * or there is not enough room in the array. 1037 * @since 1.3 1038 */ 1039 private static int decode4to3( 1040 byte[] source, int srcOffset, 1041 byte[] destination, int destOffset, int options ) { 1042 1043 // Lots of error checking and exception throwing 1044 if( source == null ){ 1045 throw new NullPointerException( "Source array was null." ); 1046 } // end if 1047 if( destination == null ){ 1048 throw new NullPointerException( "Destination array was null." ); 1049 } // end if 1050 if( srcOffset < 0 || srcOffset + 3 >= source.length ){ 1051 throw new IllegalArgumentException( String.format( 1052 "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); 1053 } // end if 1054 if( destOffset < 0 || destOffset +2 >= destination.length ){ 1055 throw new IllegalArgumentException( String.format( 1056 "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); 1057 } // end if 1058 1059 1060 byte[] DECODABET = getDecodabet( options ); 1061 1062 // Example: Dk== 1063 if( source[ srcOffset + 2] == EQUALS_SIGN ) { 1064 // Two ways to do the same thing. Don't know which way I like best. 1065 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1066 // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); 1067 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 1068 | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); 1069 1070 destination[ destOffset ] = (byte)( outBuff >>> 16 ); 1071 return 1; 1072 } 1073 1074 // Example: DkL= 1075 else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { 1076 // Two ways to do the same thing. Don't know which way I like best. 1077 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1078 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 1079 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); 1080 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 1081 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) 1082 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); 1083 1084 destination[ destOffset ] = (byte)( outBuff >>> 16 ); 1085 destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); 1086 return 2; 1087 } 1088 1089 // Example: DkLE 1090 else { 1091 // Two ways to do the same thing. Don't know which way I like best. 1092 //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1093 // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 1094 // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) 1095 // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); 1096 int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 1097 | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) 1098 | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) 1099 | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); 1100 1101 1102 destination[ destOffset ] = (byte)( outBuff >> 16 ); 1103 destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); 1104 destination[ destOffset + 2 ] = (byte)( outBuff ); 1105 1106 return 3; 1107 } 1108 } // end decodeToBytes 1109 1110 1111 1112 1113 1114 /** 1115 * Low-level access to decoding ASCII characters in 1116 * the form of a byte array. <strong>Ignores GUNZIP option, if 1117 * it's set.</strong> This is not generally a recommended method, 1118 * although it is used internally as part of the decoding process. 1119 * Special case: if len = 0, an empty array is returned. Still, 1120 * if you need more speed and reduced memory footprint (and aren't 1121 * gzipping), consider this method. 1122 * 1123 * @param source The Base64 encoded data 1124 * @return decoded data 1125 * @since 2.3.1 1126 */ 1127 public static byte[] decode( byte[] source ) 1128 throws java.io.IOException { 1129 byte[] decoded = null; 1130// try { 1131 decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); 1132// } catch( java.io.IOException ex ) { 1133// assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); 1134// } 1135 return decoded; 1136 } 1137 1138 1139 1140 /** 1141 * Low-level access to decoding ASCII characters in 1142 * the form of a byte array. <strong>Ignores GUNZIP option, if 1143 * it's set.</strong> This is not generally a recommended method, 1144 * although it is used internally as part of the decoding process. 1145 * Special case: if len = 0, an empty array is returned. Still, 1146 * if you need more speed and reduced memory footprint (and aren't 1147 * gzipping), consider this method. 1148 * 1149 * @param source The Base64 encoded data 1150 * @param off The offset of where to begin decoding 1151 * @param len The length of characters to decode 1152 * @param options Can specify options such as alphabet type to use 1153 * @return decoded data 1154 * @throws java.io.IOException If bogus characters exist in source data 1155 * @since 1.3 1156 */ 1157 public static byte[] decode( byte[] source, int off, int len, int options ) 1158 throws java.io.IOException { 1159 1160 // Lots of error checking and exception throwing 1161 if( source == null ){ 1162 throw new NullPointerException( "Cannot decode null source array." ); 1163 } // end if 1164 if( off < 0 || off + len > source.length ){ 1165 throw new IllegalArgumentException( String.format( 1166 "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); 1167 } // end if 1168 1169 if( len == 0 ){ 1170 return new byte[0]; 1171 }else if( len < 4 ){ 1172 throw new IllegalArgumentException( 1173 "Base64-encoded string must have at least four characters, but length specified was " + len ); 1174 } // end if 1175 1176 byte[] DECODABET = getDecodabet( options ); 1177 1178 int len34 = len * 3 / 4; // Estimate on array size 1179 byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output 1180 int outBuffPosn = 0; // Keep track of where we're writing 1181 1182 byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space 1183 int b4Posn = 0; // Keep track of four byte input buffer 1184 int i = 0; // Source array counter 1185 byte sbiDecode = 0; // Special value from DECODABET 1186 1187 for( i = off; i < off+len; i++ ) { // Loop through source 1188 1189 sbiDecode = DECODABET[ source[i]&0xFF ]; 1190 1191 // White space, Equals sign, or legit Base64 character 1192 // Note the values such as -5 and -9 in the 1193 // DECODABETs at the top of the file. 1194 if( sbiDecode >= WHITE_SPACE_ENC ) { 1195 if( sbiDecode >= EQUALS_SIGN_ENC ) { 1196 b4[ b4Posn++ ] = source[i]; // Save non-whitespace 1197 if( b4Posn > 3 ) { // Time to decode? 1198 outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); 1199 b4Posn = 0; 1200 1201 // If that was the equals sign, break out of 'for' loop 1202 if( source[i] == EQUALS_SIGN ) { 1203 break; 1204 } // end if: equals sign 1205 } // end if: quartet built 1206 } // end if: equals sign or better 1207 } // end if: white space, equals sign or better 1208 else { 1209 // There's a bad input character in the Base64 stream. 1210 throw new java.io.IOException( String.format( 1211 "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); 1212 } // end else: 1213 } // each input character 1214 1215 byte[] out = new byte[ outBuffPosn ]; 1216 System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); 1217 return out; 1218 } // end decode 1219 1220 1221 1222 1223 /** 1224 * Decodes data from Base64 notation, automatically 1225 * detecting gzip-compressed data and decompressing it. 1226 * 1227 * @param s the string to decode 1228 * @return the decoded data 1229 * @throws java.io.IOException If there is a problem 1230 * @since 1.4 1231 */ 1232 public static byte[] decode( String s ) throws java.io.IOException { 1233 return decode( s, NO_OPTIONS ); 1234 } 1235 1236 1237 1238 /** 1239 * Decodes data from Base64 notation, automatically 1240 * detecting gzip-compressed data and decompressing it. 1241 * 1242 * @param s the string to decode 1243 * @param options encode options such as URL_SAFE 1244 * @return the decoded data 1245 * @throws java.io.IOException if there is an error 1246 * @throws NullPointerException if <code>s</code> is null 1247 * @since 1.4 1248 */ 1249 public static byte[] decode( String s, int options ) throws java.io.IOException { 1250 1251 if( s == null ){ 1252 throw new NullPointerException( "Input string was null." ); 1253 } // end if 1254 1255 byte[] bytes; 1256 try { 1257 bytes = s.getBytes( PREFERRED_ENCODING ); 1258 } // end try 1259 catch( java.io.UnsupportedEncodingException uee ) { 1260 bytes = s.getBytes(); 1261 } // end catch 1262 //</change> 1263 1264 // Decode 1265 bytes = decode( bytes, 0, bytes.length, options ); 1266 1267 // Check to see if it's gzip-compressed 1268 // GZIP Magic Two-Byte Number: 0x8b1f (35615) 1269 boolean dontGunzip = (options & DONT_GUNZIP) != 0; 1270 if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { 1271 1272 int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); 1273 if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { 1274 java.io.ByteArrayInputStream bais = null; 1275 java.util.zip.GZIPInputStream gzis = null; 1276 java.io.ByteArrayOutputStream baos = null; 1277 byte[] buffer = new byte[2048]; 1278 int length = 0; 1279 1280 try { 1281 baos = new java.io.ByteArrayOutputStream(); 1282 bais = new java.io.ByteArrayInputStream( bytes ); 1283 gzis = new java.util.zip.GZIPInputStream( bais ); 1284 1285 while( ( length = gzis.read( buffer ) ) >= 0 ) { 1286 baos.write(buffer,0,length); 1287 } // end while: reading input 1288 1289 // No error? Get new bytes. 1290 bytes = baos.toByteArray(); 1291 1292 } // end try 1293 catch( java.io.IOException e ) { 1294 e.printStackTrace(); 1295 // Just return originally-decoded bytes 1296 } // end catch 1297 finally { 1298 try{ baos.close(); } catch( Exception e ){} 1299 try{ gzis.close(); } catch( Exception e ){} 1300 try{ bais.close(); } catch( Exception e ){} 1301 } // end finally 1302 1303 } // end if: gzipped 1304 } // end if: bytes.length >= 2 1305 1306 return bytes; 1307 } // end decode 1308 1309 1310 1311 /** 1312 * Attempts to decode Base64 data and deserialize a Java 1313 * Object within. Returns <code>null</code> if there was an error. 1314 * 1315 * @param encodedObject The Base64 data to decode 1316 * @return The decoded and deserialized object 1317 * @throws NullPointerException if encodedObject is null 1318 * @throws java.io.IOException if there is a general error 1319 * @throws ClassNotFoundException if the decoded object is of a 1320 * class that cannot be found by the JVM 1321 * @since 1.5 1322 */ 1323 public static Object decodeToObject( String encodedObject ) 1324 throws java.io.IOException, ClassNotFoundException { 1325 return decodeToObject(encodedObject,NO_OPTIONS,null); 1326 } 1327 1328 1329 /** 1330 * Attempts to decode Base64 data and deserialize a Java 1331 * Object within. Returns <code>null</code> if there was an error. 1332 * If <code>loader</code> is not null, it will be the class loader 1333 * used when deserializing. 1334 * 1335 * @param encodedObject The Base64 data to decode 1336 * @param options Various parameters related to decoding 1337 * @param loader Optional class loader to use in deserializing classes. 1338 * @return The decoded and deserialized object 1339 * @throws NullPointerException if encodedObject is null 1340 * @throws java.io.IOException if there is a general error 1341 * @throws ClassNotFoundException if the decoded object is of a 1342 * class that cannot be found by the JVM 1343 * @since 2.3.4 1344 */ 1345 public static Object decodeToObject( 1346 String encodedObject, int options, final ClassLoader loader ) 1347 throws java.io.IOException, ClassNotFoundException { 1348 1349 // Decode and gunzip if necessary 1350 byte[] objBytes = decode( encodedObject, options ); 1351 1352 java.io.ByteArrayInputStream bais = null; 1353 java.io.ObjectInputStream ois = null; 1354 Object obj = null; 1355 1356 try { 1357 bais = new java.io.ByteArrayInputStream( objBytes ); 1358 1359 // If no custom class loader is provided, use Java's builtin OIS. 1360 if( loader == null ){ 1361 ois = new java.io.ObjectInputStream( bais ); 1362 } // end if: no loader provided 1363 1364 // Else make a customized object input stream that uses 1365 // the provided class loader. 1366 else { 1367 ois = new java.io.ObjectInputStream(bais){ 1368 @Override 1369 public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) 1370 throws java.io.IOException, ClassNotFoundException { 1371 Class<?> c = Class.forName(streamClass.getName(), false, loader); 1372 if( c == null ){ 1373 return super.resolveClass(streamClass); 1374 } else { 1375 return c; // Class loader knows of this class. 1376 } // end else: not null 1377 } // end resolveClass 1378 }; // end ois 1379 } // end else: no custom class loader 1380 1381 obj = ois.readObject(); 1382 } // end try 1383 catch( java.io.IOException e ) { 1384 throw e; // Catch and throw in order to execute finally{} 1385 } // end catch 1386 catch( ClassNotFoundException e ) { 1387 throw e; // Catch and throw in order to execute finally{} 1388 } // end catch 1389 finally { 1390 try{ bais.close(); } catch( Exception e ){} 1391 try{ ois.close(); } catch( Exception e ){} 1392 } // end finally 1393 1394 return obj; 1395 } // end decodeObject 1396 1397 1398 1399 /** 1400 * Convenience method for encoding data to a file. 1401 * 1402 * <p>As of v 2.3, if there is a error, 1403 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 1404 * In earlier versions, it just returned false, but 1405 * in retrospect that's a pretty poor way to handle it.</p> 1406 * 1407 * @param dataToEncode byte array of data to encode in base64 form 1408 * @param filename Filename for saving encoded data 1409 * @throws java.io.IOException if there is an error 1410 * @throws NullPointerException if dataToEncode is null 1411 * @since 2.1 1412 */ 1413 public static void encodeToFile( byte[] dataToEncode, String filename ) 1414 throws java.io.IOException { 1415 1416 if( dataToEncode == null ){ 1417 throw new NullPointerException( "Data to encode was null." ); 1418 } // end iff 1419 1420 OutputStream bos = null; 1421 try { 1422 bos = new OutputStream( 1423 new java.io.FileOutputStream( filename ), Base64.ENCODE ); 1424 bos.write( dataToEncode ); 1425 } // end try 1426 catch( java.io.IOException e ) { 1427 throw e; // Catch and throw to execute finally{} block 1428 } // end catch: java.io.IOException 1429 finally { 1430 try{ bos.close(); } catch( Exception e ){} 1431 } // end finally 1432 1433 } // end encodeToFile 1434 1435 1436 /** 1437 * Convenience method for decoding data to a file. 1438 * 1439 * <p>As of v 2.3, if there is a error, 1440 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 1441 * In earlier versions, it just returned false, but 1442 * in retrospect that's a pretty poor way to handle it.</p> 1443 * 1444 * @param dataToDecode Base64-encoded data as a string 1445 * @param filename Filename for saving decoded data 1446 * @throws java.io.IOException if there is an error 1447 * @since 2.1 1448 */ 1449 public static void decodeToFile( String dataToDecode, String filename ) 1450 throws java.io.IOException { 1451 1452 OutputStream bos = null; 1453 try{ 1454 bos = new OutputStream( 1455 new java.io.FileOutputStream( filename ), Base64.DECODE ); 1456 bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); 1457 } // end try 1458 catch( java.io.IOException e ) { 1459 throw e; // Catch and throw to execute finally{} block 1460 } // end catch: java.io.IOException 1461 finally { 1462 try{ bos.close(); } catch( Exception e ){} 1463 } // end finally 1464 1465 } // end decodeToFile 1466 1467 1468 1469 1470 /** 1471 * Convenience method for reading a base64-encoded 1472 * file and decoding it. 1473 * 1474 * <p>As of v 2.3, if there is a error, 1475 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 1476 * In earlier versions, it just returned false, but 1477 * in retrospect that's a pretty poor way to handle it.</p> 1478 * 1479 * @param filename Filename for reading encoded data 1480 * @return decoded byte array 1481 * @throws java.io.IOException if there is an error 1482 * @since 2.1 1483 */ 1484 public static byte[] decodeFromFile( String filename ) 1485 throws java.io.IOException { 1486 1487 byte[] decodedData = null; 1488 InputStream bis = null; 1489 try 1490 { 1491 // Set up some useful variables 1492 java.io.File file = new java.io.File( filename ); 1493 byte[] buffer = null; 1494 int length = 0; 1495 int numBytes = 0; 1496 1497 // Check for size of file 1498 if( file.length() > Integer.MAX_VALUE ) 1499 { 1500 throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); 1501 } // end if: file too big for int index 1502 buffer = new byte[ (int)file.length() ]; 1503 1504 // Open a stream 1505 bis = new InputStream( 1506 new java.io.BufferedInputStream( 1507 new java.io.FileInputStream( file ) ), Base64.DECODE ); 1508 1509 // Read until done 1510 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { 1511 length += numBytes; 1512 } // end while 1513 1514 // Save in a variable to return 1515 decodedData = new byte[ length ]; 1516 System.arraycopy( buffer, 0, decodedData, 0, length ); 1517 1518 } // end try 1519 catch( java.io.IOException e ) { 1520 throw e; // Catch and release to execute finally{} 1521 } // end catch: java.io.IOException 1522 finally { 1523 try{ bis.close(); } catch( Exception e) {} 1524 } // end finally 1525 1526 return decodedData; 1527 } // end decodeFromFile 1528 1529 1530 1531 /** 1532 * Convenience method for reading a binary file 1533 * and base64-encoding it. 1534 * 1535 * <p>As of v 2.3, if there is a error, 1536 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> 1537 * In earlier versions, it just returned false, but 1538 * in retrospect that's a pretty poor way to handle it.</p> 1539 * 1540 * @param filename Filename for reading binary data 1541 * @return base64-encoded string 1542 * @throws java.io.IOException if there is an error 1543 * @since 2.1 1544 */ 1545 public static String encodeFromFile( String filename ) 1546 throws java.io.IOException { 1547 1548 String encodedData = null; 1549 InputStream bis = null; 1550 try 1551 { 1552 // Set up some useful variables 1553 java.io.File file = new java.io.File( filename ); 1554 byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) 1555 int length = 0; 1556 int numBytes = 0; 1557 1558 // Open a stream 1559 bis = new InputStream( 1560 new java.io.BufferedInputStream( 1561 new java.io.FileInputStream( file ) ), Base64.ENCODE ); 1562 1563 // Read until done 1564 while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { 1565 length += numBytes; 1566 } // end while 1567 1568 // Save in a variable to return 1569 encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); 1570 1571 } // end try 1572 catch( java.io.IOException e ) { 1573 throw e; // Catch and release to execute finally{} 1574 } // end catch: java.io.IOException 1575 finally { 1576 try{ bis.close(); } catch( Exception e) {} 1577 } // end finally 1578 1579 return encodedData; 1580 } // end encodeFromFile 1581 1582 /** 1583 * Reads <code>infile</code> and encodes it to <code>outfile</code>. 1584 * 1585 * @param infile Input file 1586 * @param outfile Output file 1587 * @throws java.io.IOException if there is an error 1588 * @since 2.2 1589 */ 1590 public static void encodeFileToFile( String infile, String outfile ) 1591 throws java.io.IOException { 1592 1593 String encoded = Base64.encodeFromFile( infile ); 1594 java.io.OutputStream out = null; 1595 try{ 1596 out = new java.io.BufferedOutputStream( 1597 new java.io.FileOutputStream( outfile ) ); 1598 out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. 1599 } // end try 1600 catch( java.io.IOException e ) { 1601 throw e; // Catch and release to execute finally{} 1602 } // end catch 1603 finally { 1604 try { out.close(); } 1605 catch( Exception ex ){} 1606 } // end finally 1607 } // end encodeFileToFile 1608 1609 1610 /** 1611 * Reads <code>infile</code> and decodes it to <code>outfile</code>. 1612 * 1613 * @param infile Input file 1614 * @param outfile Output file 1615 * @throws java.io.IOException if there is an error 1616 * @since 2.2 1617 */ 1618 public static void decodeFileToFile( String infile, String outfile ) 1619 throws java.io.IOException { 1620 1621 byte[] decoded = Base64.decodeFromFile( infile ); 1622 java.io.OutputStream out = null; 1623 try{ 1624 out = new java.io.BufferedOutputStream( 1625 new java.io.FileOutputStream( outfile ) ); 1626 out.write( decoded ); 1627 } // end try 1628 catch( java.io.IOException e ) { 1629 throw e; // Catch and release to execute finally{} 1630 } // end catch 1631 finally { 1632 try { out.close(); } 1633 catch( Exception ex ){} 1634 } // end finally 1635 } // end decodeFileToFile 1636 1637 1638 /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ 1639 1640 1641 1642 /** 1643 * A {@link Base64.InputStream} will read data from another 1644 * <code>java.io.InputStream</code>, given in the constructor, 1645 * and encode/decode to/from Base64 notation on the fly. 1646 * 1647 * @see Base64 1648 * @since 1.3 1649 */ 1650 public static class InputStream extends java.io.FilterInputStream { 1651 1652 private boolean encode; // Encoding or decoding 1653 private int position; // Current position in the buffer 1654 private byte[] buffer; // Small buffer holding converted data 1655 private int bufferLength; // Length of buffer (3 or 4) 1656 private int numSigBytes; // Number of meaningful bytes in the buffer 1657 private int lineLength; 1658 private boolean breakLines; // Break lines at less than 80 characters 1659 private int options; // Record options used to create the stream. 1660 private byte[] decodabet; // Local copies to avoid extra method calls 1661 1662 1663 /** 1664 * Constructs a {@link Base64.InputStream} in DECODE mode. 1665 * 1666 * @param in the <code>java.io.InputStream</code> from which to read data. 1667 * @since 1.3 1668 */ 1669 public InputStream( java.io.InputStream in ) { 1670 this( in, DECODE ); 1671 } // end constructor 1672 1673 1674 /** 1675 * Constructs a {@link Base64.InputStream} in 1676 * either ENCODE or DECODE mode. 1677 * <p> 1678 * Valid options:<pre> 1679 * ENCODE or DECODE: Encode or Decode as data is read. 1680 * DO_BREAK_LINES: break lines at 76 characters 1681 * (only meaningful when encoding) 1682 * </pre> 1683 * <p> 1684 * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> 1685 * 1686 * 1687 * @param in the <code>java.io.InputStream</code> from which to read data. 1688 * @param options Specified options 1689 * @see Base64#ENCODE 1690 * @see Base64#DECODE 1691 * @see Base64#DO_BREAK_LINES 1692 * @since 2.0 1693 */ 1694 public InputStream( java.io.InputStream in, int options ) { 1695 1696 super( in ); 1697 this.options = options; // Record for later 1698 this.breakLines = (options & DO_BREAK_LINES) > 0; 1699 this.encode = (options & ENCODE) > 0; 1700 this.bufferLength = encode ? 4 : 3; 1701 this.buffer = new byte[ bufferLength ]; 1702 this.position = -1; 1703 this.lineLength = 0; 1704 this.decodabet = getDecodabet(options); 1705 } // end constructor 1706 1707 /** 1708 * Reads enough of the input stream to convert 1709 * to/from Base64 and returns the next byte. 1710 * 1711 * @return next byte 1712 * @since 1.3 1713 */ 1714 @Override 1715 public int read() throws java.io.IOException { 1716 1717 // Do we need to get data? 1718 if( position < 0 ) { 1719 if( encode ) { 1720 byte[] b3 = new byte[3]; 1721 int numBinaryBytes = 0; 1722 for( int i = 0; i < 3; i++ ) { 1723 int b = in.read(); 1724 1725 // If end of stream, b is -1. 1726 if( b >= 0 ) { 1727 b3[i] = (byte)b; 1728 numBinaryBytes++; 1729 } else { 1730 break; // out of for loop 1731 } // end else: end of stream 1732 1733 } // end for: each needed input byte 1734 1735 if( numBinaryBytes > 0 ) { 1736 encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); 1737 position = 0; 1738 numSigBytes = 4; 1739 } // end if: got data 1740 else { 1741 return -1; // Must be end of stream 1742 } // end else 1743 } // end if: encoding 1744 1745 // Else decoding 1746 else { 1747 byte[] b4 = new byte[4]; 1748 int i = 0; 1749 for( i = 0; i < 4; i++ ) { 1750 // Read four "meaningful" bytes: 1751 int b = 0; 1752 do{ b = in.read(); } 1753 while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); 1754 1755 if( b < 0 ) { 1756 break; // Reads a -1 if end of stream 1757 } // end if: end of stream 1758 1759 b4[i] = (byte)b; 1760 } // end for: each needed input byte 1761 1762 if( i == 4 ) { 1763 numSigBytes = decode4to3( b4, 0, buffer, 0, options ); 1764 position = 0; 1765 } // end if: got four characters 1766 else if( i == 0 ){ 1767 return -1; 1768 } // end else if: also padded correctly 1769 else { 1770 // Must have broken out from above. 1771 throw new java.io.IOException( "Improperly padded Base64 input." ); 1772 } // end 1773 1774 } // end else: decode 1775 } // end else: get data 1776 1777 // Got data? 1778 if( position >= 0 ) { 1779 // End of relevant data? 1780 if( /*!encode &&*/ position >= numSigBytes ){ 1781 return -1; 1782 } // end if: got data 1783 1784 if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { 1785 lineLength = 0; 1786 return '\n'; 1787 } // end if 1788 else { 1789 lineLength++; // This isn't important when decoding 1790 // but throwing an extra "if" seems 1791 // just as wasteful. 1792 1793 int b = buffer[ position++ ]; 1794 1795 if( position >= bufferLength ) { 1796 position = -1; 1797 } // end if: end 1798 1799 return b & 0xFF; // This is how you "cast" a byte that's 1800 // intended to be unsigned. 1801 } // end else 1802 } // end if: position >= 0 1803 1804 // Else error 1805 else { 1806 throw new java.io.IOException( "Error in Base64 code reading stream." ); 1807 } // end else 1808 } // end read 1809 1810 1811 /** 1812 * Calls {@link #read()} repeatedly until the end of stream 1813 * is reached or <var>len</var> bytes are read. 1814 * Returns number of bytes read into array or -1 if 1815 * end of stream is encountered. 1816 * 1817 * @param dest array to hold values 1818 * @param off offset for array 1819 * @param len max number of bytes to read into array 1820 * @return bytes read into array or -1 if end of stream is encountered. 1821 * @since 1.3 1822 */ 1823 @Override 1824 public int read( byte[] dest, int off, int len ) 1825 throws java.io.IOException { 1826 int i; 1827 int b; 1828 for( i = 0; i < len; i++ ) { 1829 b = read(); 1830 1831 if( b >= 0 ) { 1832 dest[off + i] = (byte) b; 1833 } 1834 else if( i == 0 ) { 1835 return -1; 1836 } 1837 else { 1838 break; // Out of 'for' loop 1839 } // Out of 'for' loop 1840 } // end for: each byte read 1841 return i; 1842 } // end read 1843 1844 } // end inner class InputStream 1845 1846 1847 1848 1849 1850 1851 /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ 1852 1853 1854 1855 /** 1856 * A {@link Base64.OutputStream} will write data to another 1857 * <code>java.io.OutputStream</code>, given in the constructor, 1858 * and encode/decode to/from Base64 notation on the fly. 1859 * 1860 * @see Base64 1861 * @since 1.3 1862 */ 1863 public static class OutputStream extends java.io.FilterOutputStream { 1864 1865 private boolean encode; 1866 private int position; 1867 private byte[] buffer; 1868 private int bufferLength; 1869 private int lineLength; 1870 private boolean breakLines; 1871 private byte[] b4; // Scratch used in a few places 1872 private boolean suspendEncoding; 1873 private int options; // Record for later 1874 private byte[] decodabet; // Local copies to avoid extra method calls 1875 1876 /** 1877 * Constructs a {@link Base64.OutputStream} in ENCODE mode. 1878 * 1879 * @param out the <code>java.io.OutputStream</code> to which data will be written. 1880 * @since 1.3 1881 */ 1882 public OutputStream( java.io.OutputStream out ) { 1883 this( out, ENCODE ); 1884 } // end constructor 1885 1886 1887 /** 1888 * Constructs a {@link Base64.OutputStream} in 1889 * either ENCODE or DECODE mode. 1890 * <p> 1891 * Valid options:<pre> 1892 * ENCODE or DECODE: Encode or Decode as data is read. 1893 * DO_BREAK_LINES: don't break lines at 76 characters 1894 * (only meaningful when encoding) 1895 * </pre> 1896 * <p> 1897 * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> 1898 * 1899 * @param out the <code>java.io.OutputStream</code> to which data will be written. 1900 * @param options Specified options. 1901 * @see Base64#ENCODE 1902 * @see Base64#DECODE 1903 * @see Base64#DO_BREAK_LINES 1904 * @since 1.3 1905 */ 1906 public OutputStream( java.io.OutputStream out, int options ) { 1907 super( out ); 1908 this.breakLines = (options & DO_BREAK_LINES) != 0; 1909 this.encode = (options & ENCODE) != 0; 1910 this.bufferLength = encode ? 3 : 4; 1911 this.buffer = new byte[ bufferLength ]; 1912 this.position = 0; 1913 this.lineLength = 0; 1914 this.suspendEncoding = false; 1915 this.b4 = new byte[4]; 1916 this.options = options; 1917 this.decodabet = getDecodabet(options); 1918 } // end constructor 1919 1920 1921 /** 1922 * Writes the byte to the output stream after 1923 * converting to/from Base64 notation. 1924 * When encoding, bytes are buffered three 1925 * at a time before the output stream actually 1926 * gets a write() call. 1927 * When decoding, bytes are buffered four 1928 * at a time. 1929 * 1930 * @param theByte the byte to write 1931 * @since 1.3 1932 */ 1933 @Override 1934 public void write(int theByte) 1935 throws java.io.IOException { 1936 // Encoding suspended? 1937 if( suspendEncoding ) { 1938 this.out.write( theByte ); 1939 return; 1940 } // end if: supsended 1941 1942 // Encode? 1943 if( encode ) { 1944 buffer[ position++ ] = (byte)theByte; 1945 if( position >= bufferLength ) { // Enough to encode. 1946 1947 this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); 1948 1949 lineLength += 4; 1950 if( breakLines && lineLength >= MAX_LINE_LENGTH ) { 1951 this.out.write( NEW_LINE ); 1952 lineLength = 0; 1953 } // end if: end of line 1954 1955 position = 0; 1956 } // end if: enough to output 1957 } // end if: encoding 1958 1959 // Else, Decoding 1960 else { 1961 // Meaningful Base64 character? 1962 if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { 1963 buffer[ position++ ] = (byte)theByte; 1964 if( position >= bufferLength ) { // Enough to output. 1965 1966 int len = Base64.decode4to3( buffer, 0, b4, 0, options ); 1967 out.write( b4, 0, len ); 1968 position = 0; 1969 } // end if: enough to output 1970 } // end if: meaningful base64 character 1971 else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { 1972 throw new java.io.IOException( "Invalid character in Base64 data." ); 1973 } // end else: not white space either 1974 } // end else: decoding 1975 } // end write 1976 1977 1978 1979 /** 1980 * Calls {@link #write(int)} repeatedly until <var>len</var> 1981 * bytes are written. 1982 * 1983 * @param theBytes array from which to read bytes 1984 * @param off offset for array 1985 * @param len max number of bytes to read into array 1986 * @since 1.3 1987 */ 1988 @Override 1989 public void write( byte[] theBytes, int off, int len ) 1990 throws java.io.IOException { 1991 // Encoding suspended? 1992 if( suspendEncoding ) { 1993 this.out.write( theBytes, off, len ); 1994 return; 1995 } // end if: supsended 1996 1997 for( int i = 0; i < len; i++ ) { 1998 write( theBytes[ off + i ] ); 1999 } // end for: each byte written 2000 2001 } // end write 2002 2003 2004 2005 /** 2006 * Method added by PHIL. [Thanks, PHIL. -Rob] 2007 * This pads the buffer without closing the stream. 2008 * @throws java.io.IOException if there's an error. 2009 */ 2010 public void flushBase64() throws java.io.IOException { 2011 if( position > 0 ) { 2012 if( encode ) { 2013 out.write( encode3to4( b4, buffer, position, options ) ); 2014 position = 0; 2015 } // end if: encoding 2016 else { 2017 throw new java.io.IOException( "Base64 input not properly padded." ); 2018 } // end else: decoding 2019 } // end if: buffer partially full 2020 2021 } // end flush 2022 2023 2024 /** 2025 * Flushes and closes (I think, in the superclass) the stream. 2026 * 2027 * @since 1.3 2028 */ 2029 @Override 2030 public void close() throws java.io.IOException { 2031 // 1. Ensure that pending characters are written 2032 flushBase64(); 2033 2034 // 2. Actually close the stream 2035 // Base class both flushes and closes. 2036 super.close(); 2037 2038 buffer = null; 2039 out = null; 2040 } // end close 2041 2042 2043 2044 /** 2045 * Suspends encoding of the stream. 2046 * May be helpful if you need to embed a piece of 2047 * base64-encoded data in a stream. 2048 * 2049 * @throws java.io.IOException if there's an error flushing 2050 * @since 1.5.1 2051 */ 2052 public void suspendEncoding() throws java.io.IOException { 2053 flushBase64(); 2054 this.suspendEncoding = true; 2055 } // end suspendEncoding 2056 2057 2058 /** 2059 * Resumes encoding of the stream. 2060 * May be helpful if you need to embed a piece of 2061 * base64-encoded data in a stream. 2062 * 2063 * @since 1.5.1 2064 */ 2065 public void resumeEncoding() { 2066 this.suspendEncoding = false; 2067 } // end resumeEncoding 2068 2069 2070 2071 } // end inner class OutputStream 2072 2073 2074} // end class Base64