Base64.java 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver;
  16. import java.io.BufferedReader;
  17. import java.io.IOException;
  18. import java.io.InputStreamReader;
  19. import com.l2jserver.gameserver.util.StringUtil;
  20. /**
  21. * Encodes and decodes to and from Base64 notation.
  22. *
  23. * The source is based on the work of Robert Harder
  24. *
  25. * <p>
  26. * I am placing this code in the Public Domain. Do with it as you will. This
  27. * software comes with no guarantees or warranties but with plenty of
  28. * well-wishing instead! Please visit <a
  29. * href="http://iharder.net/xmlizable">http://iharder.net/base64</a>
  30. * periodically to check for updates or to contribute improvements.
  31. * </p>
  32. *
  33. * @author Robert Harder
  34. * @author rob@iharder.net
  35. * @version 2.0
  36. */
  37. public class Base64
  38. {
  39. /* P U B L I C F I E L D S */
  40. /** No options specified. Value is zero. */
  41. public final static int NO_OPTIONS = 0;
  42. /** Specify encoding. */
  43. public final static int ENCODE = 1;
  44. /** Specify decoding. */
  45. public final static int DECODE = 0;
  46. /** Specify that data should be gzip-compressed. */
  47. public final static int GZIP = 2;
  48. /** Don't break lines when encoding (violates strict Base64 specification) */
  49. public final static int DONT_BREAK_LINES = 8;
  50. /* P R I V A T E F I E L D S */
  51. /** Maximum line length (76) of Base64 output. */
  52. private final static int MAX_LINE_LENGTH = 76;
  53. /** The equals sign (=) as a byte. */
  54. private final static byte EQUALS_SIGN = (byte) '=';
  55. /** The new line character (\n) as a byte. */
  56. private final static byte NEW_LINE = (byte) '\n';
  57. /** Preferred encoding. */
  58. private final static String PREFERRED_ENCODING = "UTF-8";
  59. /** The 64 valid Base64 values. */
  60. private final static byte[] ALPHABET;
  61. private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */
  62. { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
  63. (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
  64. (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
  65. (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b',
  66. (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i',
  67. (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
  68. (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w',
  69. (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
  70. (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+',
  71. (byte) '/' };
  72. public static void main(String[] args) throws IOException
  73. {
  74. BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  75. System.out.print("Enter String to encode: ");
  76. System.out.println(Base64.encodeBytes(bf.readLine().getBytes()));
  77. }
  78. /** Determine which ALPHABET to use. */
  79. static
  80. {
  81. byte[] __bytes;
  82. try
  83. {
  84. __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes(PREFERRED_ENCODING);
  85. } // end try
  86. catch (java.io.UnsupportedEncodingException use)
  87. {
  88. __bytes = _NATIVE_ALPHABET; // Fall back to native encoding
  89. } // end catch
  90. ALPHABET = __bytes;
  91. } // end static
  92. /**
  93. * Translates a Base64 value to either its 6-bit reconstruction value or a
  94. * negative number indicating some other meaning.
  95. **/
  96. final static byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
  97. -5, -5, // Whitespace: Tab and Linefeed
  98. -9, -9, // Decimal 11 - 12
  99. -5, // Whitespace: Carriage Return
  100. -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
  101. -9, -9, -9, -9, -9, // Decimal 27 - 31
  102. -5, // Whitespace: Space
  103. -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
  104. 62, // Plus sign at decimal 43
  105. -9, -9, -9, // Decimal 44 - 46
  106. 63, // Slash at decimal 47
  107. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
  108. -9, -9, -9, // Decimal 58 - 60
  109. -1, // Equals sign at decimal 61
  110. -9, -9, -9, // Decimal 62 - 64
  111. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
  112. 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
  113. -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
  114. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
  115. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
  116. -9, -9, -9, -9 // Decimal 123 - 126
  117. /*
  118. * ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
  119. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
  120. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
  121. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
  122. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
  123. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
  124. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
  125. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
  126. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
  127. * -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
  128. */
  129. };
  130. // private final static byte BAD_ENCODING = -9; // Indicates error in encoding
  131. private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
  132. private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
  133. /** Defeats instantiation. */
  134. private Base64()
  135. {
  136. }
  137. /* E N C O D I N G M E T H O D S */
  138. // /**
  139. // * Encodes the first three bytes of array <var>threeBytes</var>
  140. // * and returns a four-byte array in Base64 notation.
  141. // *
  142. // * @param threeBytes the array to convert
  143. // * @return four byte array in Base64 notation.
  144. // * @since 1.3
  145. // */
  146. // private static byte[] encode3to4( byte[] threeBytes )
  147. // {
  148. // return encode3to4( threeBytes, 3 );
  149. // } // end encodeToBytes
  150. // /**
  151. // * Encodes up to the first three bytes of array <var>threeBytes</var>
  152. // * and returns a four-byte array in Base64 notation.
  153. // * The actual number of significant bytes in your array is
  154. // * given by <var>numSigBytes</var>.
  155. // * The array <var>threeBytes</var> needs only be as big as
  156. // * <var>numSigBytes</var>.
  157. // *
  158. // * @param threeBytes the array to convert
  159. // * @param numSigBytes the number of significant bytes in your array
  160. // * @return four byte array in Base64 notation.
  161. // * @since 1.3
  162. // */
  163. // private static byte[] encode3to4( byte[] threeBytes, int numSigBytes )
  164. // {
  165. // byte[] dest = new byte[4];
  166. // encode3to4( threeBytes, 0, numSigBytes, dest, 0 );
  167. // return dest;
  168. // }
  169. /**
  170. * Encodes up to the first three bytes of array <var>threeBytes</var> and
  171. * returns a four-byte array in Base64 notation. The actual number of
  172. * significant bytes in your array is given by <var>numSigBytes</var>. The
  173. * array <var>threeBytes</var> needs only be as big as
  174. * <var>numSigBytes</var>. Code can reuse a byte array by passing a
  175. * four-byte array as <var>b4</var>.
  176. *
  177. * @param b4
  178. * A reusable byte array to reduce array instantiation
  179. * @param threeBytes
  180. * the array to convert
  181. * @param numSigBytes
  182. * the number of significant bytes in your array
  183. * @return four byte array in Base64 notation.
  184. * @since 1.5.1
  185. */
  186. static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes)
  187. {
  188. encode3to4(threeBytes, 0, numSigBytes, b4, 0);
  189. return b4;
  190. } // end encode3to4
  191. /**
  192. * Encodes up to three bytes of the array <var>source</var> and writes the
  193. * resulting four Base64 bytes to <var>destination</var>. The source and
  194. * destination arrays can be manipulated anywhere along their length by
  195. * specifying <var>srcOffset</var> and <var>destOffset</var>. This method
  196. * does not check to make sure your arrays are large enough to accomodate
  197. * <var>srcOffset</var> + 3 for the <var>source</var> array or
  198. * <var>destOffset</var> + 4 for the <var>destination</var> array. The
  199. * actual number of significant bytes in your array is given by
  200. * <var>numSigBytes</var>.
  201. *
  202. * @param source
  203. * the array to convert
  204. * @param srcOffset
  205. * the index where conversion begins
  206. * @param numSigBytes
  207. * the number of significant bytes in your array
  208. * @param destination
  209. * the array to hold the conversion
  210. * @param destOffset
  211. * the index where output will be put
  212. * @return the <var>destination</var> array
  213. * @since 1.3
  214. */
  215. static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination,
  216. int destOffset)
  217. {
  218. // 1 2 3
  219. // 01234567890123456789012345678901 Bit position
  220. // --------000000001111111122222222 Array position from threeBytes
  221. // --------| || || || | Six bit groups to index ALPHABET
  222. // >>18 >>12 >> 6 >> 0 Right shift necessary
  223. // 0x3f 0x3f 0x3f Additional AND
  224. // Create buffer with zero-padding if there are only one or two
  225. // significant bytes passed in the array.
  226. // We have to shift left 24 in order to flush out the 1's that appear
  227. // when Java treats a value as negative that is cast from a byte to an
  228. // int.
  229. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
  230. | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
  231. | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
  232. switch (numSigBytes)
  233. {
  234. case 3:
  235. destination[destOffset] = ALPHABET[(inBuff >>> 18)];
  236. destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
  237. destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
  238. destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
  239. return destination;
  240. case 2:
  241. destination[destOffset] = ALPHABET[(inBuff >>> 18)];
  242. destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
  243. destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
  244. destination[destOffset + 3] = EQUALS_SIGN;
  245. return destination;
  246. case 1:
  247. destination[destOffset] = ALPHABET[(inBuff >>> 18)];
  248. destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
  249. destination[destOffset + 2] = EQUALS_SIGN;
  250. destination[destOffset + 3] = EQUALS_SIGN;
  251. return destination;
  252. default:
  253. return destination;
  254. } // end switch
  255. } // end encode3to4
  256. /**
  257. * Serializes an object and returns the Base64-encoded version of that
  258. * serialized object. If the object cannot be serialized or there is another
  259. * error, the method will return <tt>null</tt>. The object is not
  260. * GZip-compressed before being encoded.
  261. *
  262. * @param serializableObject
  263. * The object to encode
  264. * @return The Base64-encoded object
  265. * @since 1.4
  266. */
  267. public static String encodeObject(java.io.Serializable serializableObject)
  268. {
  269. return encodeObject(serializableObject, NO_OPTIONS);
  270. } // end encodeObject
  271. /**
  272. * Serializes an object and returns the Base64-encoded version of that
  273. * serialized object. If the object cannot be serialized or there is another
  274. * error, the method will return <tt>null</tt>.
  275. * <p>
  276. * Valid options:
  277. *
  278. * <pre>
  279. * GZIP: gzip-compresses object before encoding it.
  280. * DONT_BREAK_LINES: don't break lines at 76 characters
  281. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  282. * </pre>
  283. * <p>
  284. * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
  285. * <p>
  286. * Example:
  287. * <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  288. *
  289. * @param serializableObject
  290. * The object to encode
  291. * @options Specified options
  292. * @return The Base64-encoded object
  293. * @see Base64#GZIP
  294. * @see Base64#DONT_BREAK_LINES
  295. * @since 2.0
  296. */
  297. public static String encodeObject(java.io.Serializable serializableObject, int options)
  298. {
  299. // Streams
  300. java.io.ByteArrayOutputStream baos = null;
  301. java.io.OutputStream b64os = null;
  302. java.io.ObjectOutputStream oos = null;
  303. java.util.zip.GZIPOutputStream gzos = null;
  304. // Isolate options
  305. int gzip = (options & GZIP);
  306. int dontBreakLines = (options & DONT_BREAK_LINES);
  307. try
  308. {
  309. // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
  310. baos = new java.io.ByteArrayOutputStream();
  311. b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);
  312. // GZip?
  313. if (gzip == GZIP)
  314. {
  315. gzos = new java.util.zip.GZIPOutputStream(b64os);
  316. oos = new java.io.ObjectOutputStream(gzos);
  317. } // end if: gzip
  318. else
  319. oos = new java.io.ObjectOutputStream(b64os);
  320. oos.writeObject(serializableObject);
  321. } // end try
  322. catch (java.io.IOException e)
  323. {
  324. e.printStackTrace();
  325. return null;
  326. } // end catch
  327. finally
  328. {
  329. try
  330. {
  331. oos.close();
  332. }
  333. catch (Exception e)
  334. {
  335. }
  336. try
  337. {
  338. gzos.close();
  339. }
  340. catch (Exception e)
  341. {
  342. }
  343. try
  344. {
  345. b64os.close();
  346. }
  347. catch (Exception e)
  348. {
  349. }
  350. try
  351. {
  352. baos.close();
  353. }
  354. catch (Exception e)
  355. {
  356. }
  357. } // end finally
  358. // Return value according to relevant encoding.
  359. try
  360. {
  361. return new String(baos.toByteArray(), PREFERRED_ENCODING);
  362. } // end try
  363. catch (java.io.UnsupportedEncodingException uue)
  364. {
  365. return new String(baos.toByteArray());
  366. } // end catch
  367. } // end encode
  368. /**
  369. * Encodes a byte array into Base64 notation. Does not GZip-compress data.
  370. *
  371. * @param source
  372. * The data to convert
  373. * @since 1.4
  374. */
  375. public static String encodeBytes(byte[] source)
  376. {
  377. return encodeBytes(source, 0, source.length, NO_OPTIONS);
  378. } // end encodeBytes
  379. /**
  380. * Encodes a byte array into Base64 notation.
  381. * <p>
  382. * Valid options:
  383. *
  384. * <pre>
  385. * GZIP: gzip-compresses object before encoding it.
  386. * DONT_BREAK_LINES: don't break lines at 76 characters
  387. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  388. * </pre>
  389. * <p>
  390. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  391. * <p>
  392. * Example:
  393. * <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  394. *
  395. *
  396. * @param source
  397. * The data to convert
  398. * @param options
  399. * Specified options
  400. * @see Base64#GZIP
  401. * @see Base64#DONT_BREAK_LINES
  402. * @since 2.0
  403. */
  404. public static String encodeBytes(byte[] source, int options)
  405. {
  406. return encodeBytes(source, 0, source.length, options);
  407. } // end encodeBytes
  408. /**
  409. * Encodes a byte array into Base64 notation. Does not GZip-compress data.
  410. *
  411. * @param source
  412. * The data to convert
  413. * @param off
  414. * Offset in array where conversion should begin
  415. * @param len
  416. * Length of data to convert
  417. * @since 1.4
  418. */
  419. public static String encodeBytes(byte[] source, int off, int len)
  420. {
  421. return encodeBytes(source, off, len, NO_OPTIONS);
  422. } // end encodeBytes
  423. /**
  424. * Encodes a byte array into Base64 notation.
  425. * <p>
  426. * Valid options:
  427. *
  428. * <pre>
  429. * GZIP: gzip-compresses object before encoding it.
  430. * DONT_BREAK_LINES: don't break lines at 76 characters
  431. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  432. * </pre>
  433. * <p>
  434. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  435. * <p>
  436. * Example:
  437. * <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  438. *
  439. *
  440. * @param source
  441. * The data to convert
  442. * @param off
  443. * Offset in array where conversion should begin
  444. * @param len
  445. * Length of data to convert
  446. * @param breakLines
  447. * Break lines at 80 characters or less.
  448. * @param options
  449. * Specified options
  450. * @see Base64#GZIP
  451. * @see Base64#DONT_BREAK_LINES
  452. * @since 2.0
  453. */
  454. public static String encodeBytes(byte[] source, int off, int len, int options)
  455. {
  456. // Isolate options
  457. int dontBreakLines = (options & DONT_BREAK_LINES);
  458. int gzip = (options & GZIP);
  459. // Compress?
  460. if (gzip == GZIP)
  461. {
  462. java.io.ByteArrayOutputStream baos = null;
  463. java.util.zip.GZIPOutputStream gzos = null;
  464. Base64.OutputStream b64os = null;
  465. try
  466. {
  467. // GZip -> Base64 -> ByteArray
  468. baos = new java.io.ByteArrayOutputStream();
  469. b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);
  470. gzos = new java.util.zip.GZIPOutputStream(b64os);
  471. gzos.write(source, off, len);
  472. gzos.close();
  473. } // end try
  474. catch (java.io.IOException e)
  475. {
  476. e.printStackTrace();
  477. return null;
  478. } // end catch
  479. finally
  480. {
  481. try
  482. {
  483. gzos.close();
  484. }
  485. catch (Exception e)
  486. {
  487. }
  488. try
  489. {
  490. b64os.close();
  491. }
  492. catch (Exception e)
  493. {
  494. }
  495. try
  496. {
  497. baos.close();
  498. }
  499. catch (Exception e)
  500. {
  501. }
  502. } // end finally
  503. // Return value according to relevant encoding.
  504. try
  505. {
  506. return new String(baos.toByteArray(), PREFERRED_ENCODING);
  507. } // end try
  508. catch (java.io.UnsupportedEncodingException uue)
  509. {
  510. return new String(baos.toByteArray());
  511. } // end catch
  512. } // end if: compress
  513. // Convert option to boolean in way that code likes it.
  514. boolean breakLines = dontBreakLines == 0;
  515. int len43 = len * 4 / 3;
  516. byte[] outBuff = new byte[(len43) // Main 4:3
  517. + ((len % 3) > 0 ? 4 : 0) // Account for padding
  518. + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines
  519. int d = 0;
  520. int e = 0;
  521. int len2 = len - 2;
  522. int lineLength = 0;
  523. for (; d < len2; d += 3, e += 4)
  524. {
  525. encode3to4(source, d + off, 3, outBuff, e);
  526. lineLength += 4;
  527. if (breakLines && lineLength == MAX_LINE_LENGTH)
  528. {
  529. outBuff[e + 4] = NEW_LINE;
  530. e++;
  531. lineLength = 0;
  532. } // end if: end of line
  533. } // en dfor: each piece of array
  534. if (d < len)
  535. {
  536. encode3to4(source, d + off, len - d, outBuff, e);
  537. e += 4;
  538. } // end if: some padding needed
  539. // Return value according to relevant encoding.
  540. try
  541. {
  542. return new String(outBuff, 0, e, PREFERRED_ENCODING);
  543. } // end try
  544. catch (java.io.UnsupportedEncodingException uue)
  545. {
  546. return new String(outBuff, 0, e);
  547. } // end catch
  548. // end else: don't compress
  549. } // end encodeBytes
  550. /* D E C O D I N G M E T H O D S */
  551. // /**
  552. // * Decodes the first four bytes of array <var>fourBytes</var>
  553. // * and returns an array up to three bytes long with the
  554. // * decoded values.
  555. // *
  556. // * @param fourBytes the array with Base64 content
  557. // * @return array with decoded values
  558. // * @since 1.3
  559. // */
  560. // private static byte[] decode4to3( byte[] fourBytes )
  561. // {
  562. // byte[] outBuff1 = new byte[3];
  563. // int count = decode4to3( fourBytes, 0, outBuff1, 0 );
  564. // byte[] outBuff2 = new byte[ count ];
  565. //
  566. // for( int i = 0; i < count; i++ )
  567. // outBuff2[i] = outBuff1[i];
  568. //
  569. // return outBuff2;
  570. // }
  571. /**
  572. * Decodes four bytes from array <var>source</var> and writes the resulting
  573. * bytes (up to three of them) to <var>destination</var>. The source and
  574. * destination arrays can be manipulated anywhere along their length by
  575. * specifying <var>srcOffset</var> and <var>destOffset</var>. This method
  576. * does not check to make sure your arrays are large enough to accomodate
  577. * <var>srcOffset</var> + 4 for the <var>source</var> array or
  578. * <var>destOffset</var> + 3 for the <var>destination</var> array. This
  579. * method returns the actual number of bytes that were converted from the
  580. * Base64 encoding.
  581. *
  582. *
  583. * @param source
  584. * the array to convert
  585. * @param srcOffset
  586. * the index where conversion begins
  587. * @param destination
  588. * the array to hold the conversion
  589. * @param destOffset
  590. * the index where output will be put
  591. * @return the number of decoded bytes converted
  592. * @since 1.3
  593. */
  594. static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset)
  595. {
  596. // Example: Dk==
  597. if (source[srcOffset + 2] == EQUALS_SIGN)
  598. {
  599. // Two ways to do the same thing. Don't know which way I like best.
  600. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
  601. // )
  602. // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
  603. int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
  604. | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
  605. destination[destOffset] = (byte) (outBuff >>> 16);
  606. return 1;
  607. }
  608. // Example: DkL=
  609. else if (source[srcOffset + 3] == EQUALS_SIGN)
  610. {
  611. // Two ways to do the same thing. Don't know which way I like best.
  612. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
  613. // )
  614. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  615. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
  616. int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
  617. | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
  618. | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
  619. destination[destOffset] = (byte) (outBuff >>> 16);
  620. destination[destOffset + 1] = (byte) (outBuff >>> 8);
  621. return 2;
  622. }
  623. // Example: DkLE
  624. else
  625. {
  626. try
  627. {
  628. // Two ways to do the same thing. Don't know which way I like
  629. // best.
  630. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 )
  631. // >>> 6 )
  632. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  633. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
  634. // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
  635. int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
  636. | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
  637. | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
  638. | ((DECODABET[source[srcOffset + 3]] & 0xFF));
  639. destination[destOffset] = (byte) (outBuff >> 16);
  640. destination[destOffset + 1] = (byte) (outBuff >> 8);
  641. destination[destOffset + 2] = (byte) (outBuff);
  642. return 3;
  643. }
  644. catch (Exception e)
  645. {
  646. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset]), ": ", String.valueOf(DECODABET[source[srcOffset]])));
  647. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset + 1]), ": ", String.valueOf(DECODABET[source[srcOffset + 1]])));
  648. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset + 2]), ": ", String.valueOf(DECODABET[source[srcOffset + 2]])));
  649. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset + 3]), ": ", String.valueOf(DECODABET[source[srcOffset + 3]])));
  650. return -1;
  651. } // end catch
  652. }
  653. } // end decodeToBytes
  654. /**
  655. * Very low-level access to decoding ASCII characters in the form of a byte
  656. * array. Does not support automatically gunzipping or any other "fancy"
  657. * features.
  658. *
  659. * @param source
  660. * The Base64 encoded data
  661. * @param off
  662. * The offset of where to begin decoding
  663. * @param len
  664. * The length of characters to decode
  665. * @return decoded data
  666. * @since 1.3
  667. */
  668. public static byte[] decode(byte[] source, int off, int len)
  669. {
  670. int len34 = len * 3 / 4;
  671. byte[] outBuff = new byte[len34]; // Upper limit on size of output
  672. int outBuffPosn = 0;
  673. byte[] b4 = new byte[4];
  674. int b4Posn = 0;
  675. int i = 0;
  676. byte sbiCrop = 0;
  677. byte sbiDecode = 0;
  678. for (i = off; i < off + len; i++)
  679. {
  680. sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
  681. sbiDecode = DECODABET[sbiCrop];
  682. if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or
  683. // better
  684. {
  685. if (sbiDecode >= EQUALS_SIGN_ENC)
  686. {
  687. b4[b4Posn++] = sbiCrop;
  688. if (b4Posn > 3)
  689. {
  690. outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
  691. b4Posn = 0;
  692. // If that was the equals sign, break out of 'for' loop
  693. if (sbiCrop == EQUALS_SIGN)
  694. break;
  695. } // end if: quartet built
  696. } // end if: equals sign or better
  697. } // end if: white space, equals sign or better
  698. else
  699. {
  700. System.err.println(StringUtil.concat("Bad Base64 input character at ", String.valueOf(i), ": ", String.valueOf(source[i]), "(decimal)"));
  701. return null;
  702. } // end else:
  703. } // each input character
  704. byte[] out = new byte[outBuffPosn];
  705. System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
  706. return out;
  707. } // end decode
  708. /**
  709. * Decodes data from Base64 notation, automatically detecting
  710. * gzip-compressed data and decompressing it.
  711. *
  712. * @param s
  713. * the string to decode
  714. * @return the decoded data
  715. * @since 1.4
  716. */
  717. public static byte[] decode(String s)
  718. {
  719. byte[] bytes;
  720. try
  721. {
  722. bytes = s.getBytes(PREFERRED_ENCODING);
  723. } // end try
  724. catch (java.io.UnsupportedEncodingException uee)
  725. {
  726. bytes = s.getBytes();
  727. } // end catch
  728. // </change>
  729. // Decode
  730. bytes = decode(bytes, 0, bytes.length);
  731. // Check to see if it's gzip-compressed
  732. // GZIP Magic Two-Byte Number: 0x8b1f (35615)
  733. if (bytes != null && // In case decoding returned null
  734. bytes.length >= 2)
  735. {
  736. int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
  737. if (bytes.length >= 4 && // Don't want to get ArrayIndexOutOfBounds
  738. // exception
  739. java.util.zip.GZIPInputStream.GZIP_MAGIC == head)
  740. {
  741. java.io.ByteArrayInputStream bais = null;
  742. java.util.zip.GZIPInputStream gzis = null;
  743. java.io.ByteArrayOutputStream baos = null;
  744. byte[] buffer = new byte[2048];
  745. int length = 0;
  746. try
  747. {
  748. baos = new java.io.ByteArrayOutputStream();
  749. bais = new java.io.ByteArrayInputStream(bytes);
  750. gzis = new java.util.zip.GZIPInputStream(bais);
  751. while ((length = gzis.read(buffer)) >= 0)
  752. {
  753. baos.write(buffer, 0, length);
  754. } // end while: reading input
  755. // No error? Get new bytes.
  756. bytes = baos.toByteArray();
  757. } // end try
  758. catch (java.io.IOException e)
  759. {
  760. // Just return originally-decoded bytes
  761. } // end catch
  762. finally
  763. {
  764. try
  765. {
  766. baos.close();
  767. }
  768. catch (Exception e)
  769. {
  770. }
  771. try
  772. {
  773. gzis.close();
  774. }
  775. catch (Exception e)
  776. {
  777. }
  778. try
  779. {
  780. bais.close();
  781. }
  782. catch (Exception e)
  783. {
  784. }
  785. } // end finally
  786. } // end if: gzipped
  787. } // end if: bytes.length >= 2
  788. return bytes;
  789. } // end decode
  790. /**
  791. * Attempts to decode Base64 data and deserialize a Java Object within.
  792. * Returns <tt>null</tt> if there was an error.
  793. *
  794. * @param encodedObject
  795. * The Base64 data to decode
  796. * @return The decoded and deserialized object
  797. * @since 1.5
  798. */
  799. public static Object decodeToObject(String encodedObject)
  800. {
  801. // Decode and gunzip if necessary
  802. byte[] objBytes = decode(encodedObject);
  803. java.io.ByteArrayInputStream bais = null;
  804. java.io.ObjectInputStream ois = null;
  805. Object obj = null;
  806. try
  807. {
  808. bais = new java.io.ByteArrayInputStream(objBytes);
  809. ois = new java.io.ObjectInputStream(bais);
  810. obj = ois.readObject();
  811. } // end try
  812. catch (java.io.IOException e)
  813. {
  814. e.printStackTrace();
  815. obj = null;
  816. } // end catch
  817. catch (java.lang.ClassNotFoundException e)
  818. {
  819. e.printStackTrace();
  820. obj = null;
  821. } // end catch
  822. finally
  823. {
  824. try
  825. {
  826. bais.close();
  827. }
  828. catch (Exception e)
  829. {
  830. }
  831. try
  832. {
  833. ois.close();
  834. }
  835. catch (Exception e)
  836. {
  837. }
  838. } // end finally
  839. return obj;
  840. } // end decodeObject
  841. /* I N N E R C L A S S I N P U T S T R E A M */
  842. /**
  843. * A {@link Base64#InputStream} will read data from another
  844. * {@link java.io.InputStream}, given in the constructor, and encode/decode
  845. * to/from Base64 notation on the fly.
  846. *
  847. * @see Base64
  848. * @see java.io.FilterInputStream
  849. * @since 1.3
  850. */
  851. public static class InputStream extends java.io.FilterInputStream
  852. {
  853. // private int options; // Options specified
  854. private boolean encode; // Encoding or decoding
  855. private int position; // Current position in the buffer
  856. private byte[] buffer; // Small buffer holding converted data
  857. private int bufferLength; // Length of buffer (3 or 4)
  858. private int numSigBytes; // Number of meaningful bytes in the buffer
  859. private int lineLength;
  860. private boolean breakLines; // Break lines at less than 80 characters
  861. /**
  862. * Constructs a {@link Base64#InputStream} in DECODE mode.
  863. *
  864. * @param in
  865. * the {@link java.io.InputStream} from which to read data.
  866. * @since 1.3
  867. */
  868. public InputStream(java.io.InputStream pIn)
  869. {
  870. this(pIn, DECODE);
  871. } // end constructor
  872. /**
  873. * Constructs a {@link Base64#InputStream} in either ENCODE or DECODE
  874. * mode.
  875. * <p>
  876. * Valid options:
  877. *
  878. * <pre>
  879. * ENCODE or DECODE: Encode or Decode as data is read.
  880. * DONT_BREAK_LINES: don't break lines at 76 characters
  881. * (only meaningful when encoding)
  882. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  883. * </pre>
  884. * <p>
  885. * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
  886. *
  887. *
  888. * @param in
  889. * the {@link java.io.InputStream} from which to read data.
  890. * @param options
  891. * Specified options
  892. * @see Base64#ENCODE
  893. * @see Base64#DECODE
  894. * @see Base64#DONT_BREAK_LINES
  895. * @since 2.0
  896. */
  897. public InputStream(java.io.InputStream pIn, int options)
  898. {
  899. super(pIn);
  900. // this.options = options;
  901. breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
  902. encode = (options & ENCODE) == ENCODE;
  903. bufferLength = encode ? 4 : 3;
  904. buffer = new byte[bufferLength];
  905. position = -1;
  906. lineLength = 0;
  907. } // end constructor
  908. /**
  909. * Reads enough of the input stream to convert to/from Base64 and
  910. * returns the next byte.
  911. *
  912. * @return next byte
  913. * @since 1.3
  914. */
  915. @Override
  916. public int read() throws java.io.IOException
  917. {
  918. // Do we need to get data?
  919. if (position < 0)
  920. {
  921. if (encode)
  922. {
  923. byte[] b3 = new byte[3];
  924. int numBinaryBytes = 0;
  925. for (int i = 0; i < 3; i++)
  926. {
  927. try
  928. {
  929. int b = in.read();
  930. // If end of stream, b is -1.
  931. if (b >= 0)
  932. {
  933. b3[i] = (byte) b;
  934. numBinaryBytes++;
  935. } // end if: not end of stream
  936. } // end try: read
  937. catch (java.io.IOException e)
  938. {
  939. // Only a problem if we got no data at all.
  940. if (i == 0)
  941. throw e;
  942. } // end catch
  943. } // end for: each needed input byte
  944. if (numBinaryBytes > 0)
  945. {
  946. encode3to4(b3, 0, numBinaryBytes, buffer, 0);
  947. position = 0;
  948. numSigBytes = 4;
  949. } // end if: got data
  950. else
  951. {
  952. return -1;
  953. } // end else
  954. } // end if: encoding
  955. // Else decoding
  956. else
  957. {
  958. byte[] b4 = new byte[4];
  959. int i = 0;
  960. for (i = 0; i < 4; i++)
  961. {
  962. // Read four "meaningful" bytes:
  963. int b = 0;
  964. do
  965. {
  966. b = in.read();
  967. }
  968. while (b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC);
  969. if (b < 0)
  970. break; // Reads a -1 if end of stream
  971. b4[i] = (byte) b;
  972. } // end for: each needed input byte
  973. if (i == 4)
  974. {
  975. numSigBytes = decode4to3(b4, 0, buffer, 0);
  976. position = 0;
  977. } // end if: got four characters
  978. else if (i == 0)
  979. {
  980. return -1;
  981. } // end else if: also padded correctly
  982. else
  983. {
  984. // Must have broken out from above.
  985. throw new java.io.IOException("Improperly padded Base64 input.");
  986. } // end
  987. } // end else: decode
  988. } // end else: get data
  989. // Got data?
  990. if (position >= 0)
  991. {
  992. // End of relevant data?
  993. if ( /* !encode && */position >= numSigBytes)
  994. return -1;
  995. if (encode && breakLines && lineLength >= MAX_LINE_LENGTH)
  996. {
  997. lineLength = 0;
  998. return '\n';
  999. } // end if
  1000. lineLength++; // This isn't important when decoding
  1001. // but throwing an extra "if" seems
  1002. // just as wasteful.
  1003. int b = buffer[position++];
  1004. if (position >= bufferLength)
  1005. position = -1;
  1006. return b & 0xFF; // This is how you "cast" a byte that's
  1007. // intended to be unsigned.
  1008. // end else
  1009. } // end if: position >= 0
  1010. // When JDK1.4 is more accepted, use an assertion here.
  1011. throw new java.io.IOException("Error in Base64 code reading stream.");
  1012. // end else
  1013. } // end read
  1014. /**
  1015. * Calls {@link #read} repeatedly until the end of stream is reached or
  1016. * <var>len</var> bytes are read. Returns number of bytes read into
  1017. * array or -1 if end of stream is encountered.
  1018. *
  1019. * @param dest
  1020. * array to hold values
  1021. * @param off
  1022. * offset for array
  1023. * @param len
  1024. * max number of bytes to read into array
  1025. * @return bytes read into array or -1 if end of stream is encountered.
  1026. * @since 1.3
  1027. */
  1028. @Override
  1029. public int read(byte[] dest, int off, int len) throws java.io.IOException
  1030. {
  1031. int i;
  1032. int b;
  1033. for (i = 0; i < len; i++)
  1034. {
  1035. b = read();
  1036. // if( b < 0 && i == 0 )
  1037. // return -1;
  1038. if (b >= 0)
  1039. dest[off + i] = (byte) b;
  1040. else if (i == 0)
  1041. return -1;
  1042. else
  1043. break; // Out of 'for' loop
  1044. } // end for: each byte read
  1045. return i;
  1046. } // end read
  1047. } // end inner class InputStream
  1048. /* I N N E R C L A S S O U T P U T S T R E A M */
  1049. /**
  1050. * A {@link Base64#OutputStream} will write data to another
  1051. * {@link java.io.OutputStream}, given in the constructor, and encode/decode
  1052. * to/from Base64 notation on the fly.
  1053. *
  1054. * @see Base64
  1055. * @see java.io.FilterOutputStream
  1056. * @since 1.3
  1057. */
  1058. public static class OutputStream extends java.io.FilterOutputStream
  1059. {
  1060. // private int options;
  1061. private boolean encode;
  1062. private int position;
  1063. private byte[] buffer;
  1064. private int bufferLength;
  1065. private int lineLength;
  1066. private boolean breakLines;
  1067. private byte[] b4; // Scratch used in a few places
  1068. private boolean suspendEncoding;
  1069. /**
  1070. * Constructs a {@link Base64#OutputStream} in ENCODE mode.
  1071. *
  1072. * @param out
  1073. * the {@link java.io.OutputStream} to which data will be
  1074. * written.
  1075. * @since 1.3
  1076. */
  1077. public OutputStream(java.io.OutputStream pOut)
  1078. {
  1079. this(pOut, ENCODE);
  1080. } // end constructor
  1081. /**
  1082. * Constructs a {@link Base64#OutputStream} in either ENCODE or DECODE
  1083. * mode.
  1084. * <p>
  1085. * Valid options:
  1086. *
  1087. * <pre>
  1088. * ENCODE or DECODE: Encode or Decode as data is read.
  1089. * DONT_BREAK_LINES: don't break lines at 76 characters
  1090. * (only meaningful when encoding)
  1091. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  1092. * </pre>
  1093. * <p>
  1094. * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
  1095. *
  1096. * @param out
  1097. * the {@link java.io.OutputStream} to which data will be
  1098. * written.
  1099. * @param options
  1100. * Specified options.
  1101. * @see Base64#ENCODE
  1102. * @see Base64#DECODE
  1103. * @see Base64#DONT_BREAK_LINES
  1104. * @since 1.3
  1105. */
  1106. public OutputStream(java.io.OutputStream pOut, int options)
  1107. {
  1108. super(pOut);
  1109. // this.options = options;
  1110. breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
  1111. encode = (options & ENCODE) == ENCODE;
  1112. bufferLength = encode ? 3 : 4;
  1113. buffer = new byte[bufferLength];
  1114. position = 0;
  1115. lineLength = 0;
  1116. suspendEncoding = false;
  1117. b4 = new byte[4];
  1118. } // end constructor
  1119. /**
  1120. * Writes the byte to the output stream after converting to/from Base64
  1121. * notation. When encoding, bytes are buffered three at a time before
  1122. * the output stream actually gets a write() call. When decoding, bytes
  1123. * are buffered four at a time.
  1124. *
  1125. * @param theByte
  1126. * the byte to write
  1127. * @since 1.3
  1128. */
  1129. @Override
  1130. public void write(int theByte) throws java.io.IOException
  1131. {
  1132. // Encoding suspended?
  1133. if (suspendEncoding)
  1134. {
  1135. super.out.write(theByte);
  1136. return;
  1137. } // end if: supsended
  1138. // Encode?
  1139. if (encode)
  1140. {
  1141. buffer[position++] = (byte) theByte;
  1142. if (position >= bufferLength) // Enough to encode.
  1143. {
  1144. out.write(encode3to4(b4, buffer, bufferLength));
  1145. lineLength += 4;
  1146. if (breakLines && lineLength >= MAX_LINE_LENGTH)
  1147. {
  1148. out.write(NEW_LINE);
  1149. lineLength = 0;
  1150. } // end if: end of line
  1151. position = 0;
  1152. } // end if: enough to output
  1153. } // end if: encoding
  1154. // Else, Decoding
  1155. else
  1156. {
  1157. // Meaningful Base64 character?
  1158. if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC)
  1159. {
  1160. buffer[position++] = (byte) theByte;
  1161. if (position >= bufferLength) // Enough to output.
  1162. {
  1163. int len = Base64.decode4to3(buffer, 0, b4, 0);
  1164. out.write(b4, 0, len);
  1165. // out.write( Base64.decode4to3( buffer ) );
  1166. position = 0;
  1167. } // end if: enough to output
  1168. } // end if: meaningful base64 character
  1169. else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC)
  1170. {
  1171. throw new java.io.IOException("Invalid character in Base64 data.");
  1172. } // end else: not white space either
  1173. } // end else: decoding
  1174. } // end write
  1175. /**
  1176. * Calls {@link #write} repeatedly until <var>len</var> bytes are
  1177. * written.
  1178. *
  1179. * @param theBytes
  1180. * array from which to read bytes
  1181. * @param off
  1182. * offset for array
  1183. * @param len
  1184. * max number of bytes to read into array
  1185. * @since 1.3
  1186. */
  1187. @Override
  1188. public void write(byte[] theBytes, int off, int len) throws java.io.IOException
  1189. {
  1190. // Encoding suspended?
  1191. if (suspendEncoding)
  1192. {
  1193. super.out.write(theBytes, off, len);
  1194. return;
  1195. } // end if: supsended
  1196. for (int i = 0; i < len; i++)
  1197. {
  1198. write(theBytes[off + i]);
  1199. } // end for: each byte written
  1200. } // end write
  1201. /**
  1202. * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer
  1203. * without closing the stream.
  1204. */
  1205. public void flushBase64() throws java.io.IOException
  1206. {
  1207. if (position > 0)
  1208. {
  1209. if (encode)
  1210. {
  1211. out.write(encode3to4(b4, buffer, position));
  1212. position = 0;
  1213. } // end if: encoding
  1214. else
  1215. {
  1216. throw new java.io.IOException("Base64 input not properly padded.");
  1217. } // end else: decoding
  1218. } // end if: buffer partially full
  1219. } // end flush
  1220. /**
  1221. * Flushes and closes (I think, in the superclass) the stream.
  1222. *
  1223. * @since 1.3
  1224. */
  1225. @Override
  1226. public void close() throws java.io.IOException
  1227. {
  1228. // 1. Ensure that pending characters are written
  1229. flushBase64();
  1230. // 2. Actually close the stream
  1231. // Base class both flushes and closes.
  1232. super.close();
  1233. buffer = null;
  1234. out = null;
  1235. } // end close
  1236. /**
  1237. * Suspends encoding of the stream. May be helpful if you need to embed
  1238. * a piece of base640-encoded data in a stream.
  1239. *
  1240. * @since 1.5.1
  1241. */
  1242. public void suspendEncoding() throws java.io.IOException
  1243. {
  1244. flushBase64();
  1245. suspendEncoding = true;
  1246. } // end suspendEncoding
  1247. /**
  1248. * Resumes encoding of the stream. May be helpful if you need to embed a
  1249. * piece of base640-encoded data in a stream.
  1250. *
  1251. * @since 1.5.1
  1252. */
  1253. public void resumeEncoding()
  1254. {
  1255. suspendEncoding = false;
  1256. } // end resumeEncoding
  1257. } // end inner class OutputStream
  1258. } // end class Base64