Base64.java 40 KB

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