Base64.java 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  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.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. }
  812. catch (java.io.IOException e)
  813. {
  814. e.printStackTrace();
  815. }
  816. catch (java.lang.ClassNotFoundException e)
  817. {
  818. e.printStackTrace();
  819. }
  820. finally
  821. {
  822. try
  823. {
  824. bais.close();
  825. }
  826. catch (Exception e)
  827. {
  828. }
  829. try
  830. {
  831. ois.close();
  832. }
  833. catch (Exception e)
  834. {
  835. }
  836. } // end finally
  837. return obj;
  838. } // end decodeObject
  839. /* I N N E R C L A S S I N P U T S T R E A M */
  840. /**
  841. * A {@link Base64#InputStream} will read data from another
  842. * {@link java.io.InputStream}, given in the constructor, and encode/decode
  843. * to/from Base64 notation on the fly.
  844. *
  845. * @see Base64
  846. * @see java.io.FilterInputStream
  847. * @since 1.3
  848. */
  849. public static class InputStream extends java.io.FilterInputStream
  850. {
  851. // private int options; // Options specified
  852. private boolean encode; // Encoding or decoding
  853. private int position; // Current position in the buffer
  854. private byte[] buffer; // Small buffer holding converted data
  855. private int bufferLength; // Length of buffer (3 or 4)
  856. private int numSigBytes; // Number of meaningful bytes in the buffer
  857. private int lineLength;
  858. private boolean breakLines; // Break lines at less than 80 characters
  859. /**
  860. * Constructs a {@link Base64#InputStream} in DECODE mode.
  861. *
  862. * @param in
  863. * the {@link java.io.InputStream} from which to read data.
  864. * @since 1.3
  865. */
  866. public InputStream(java.io.InputStream pIn)
  867. {
  868. this(pIn, DECODE);
  869. } // end constructor
  870. /**
  871. * Constructs a {@link Base64#InputStream} in either ENCODE or DECODE
  872. * mode.
  873. * <p>
  874. * Valid options:
  875. *
  876. * <pre>
  877. * ENCODE or DECODE: Encode or Decode as data is read.
  878. * DONT_BREAK_LINES: don't break lines at 76 characters
  879. * (only meaningful when encoding)
  880. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  881. * </pre>
  882. * <p>
  883. * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
  884. *
  885. *
  886. * @param in
  887. * the {@link java.io.InputStream} from which to read data.
  888. * @param options
  889. * Specified options
  890. * @see Base64#ENCODE
  891. * @see Base64#DECODE
  892. * @see Base64#DONT_BREAK_LINES
  893. * @since 2.0
  894. */
  895. public InputStream(java.io.InputStream pIn, int options)
  896. {
  897. super(pIn);
  898. // this.options = options;
  899. breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
  900. encode = (options & ENCODE) == ENCODE;
  901. bufferLength = encode ? 4 : 3;
  902. buffer = new byte[bufferLength];
  903. position = -1;
  904. lineLength = 0;
  905. } // end constructor
  906. /**
  907. * Reads enough of the input stream to convert to/from Base64 and
  908. * returns the next byte.
  909. *
  910. * @return next byte
  911. * @since 1.3
  912. */
  913. @Override
  914. public int read() throws java.io.IOException
  915. {
  916. // Do we need to get data?
  917. if (position < 0)
  918. {
  919. if (encode)
  920. {
  921. byte[] b3 = new byte[3];
  922. int numBinaryBytes = 0;
  923. for (int i = 0; i < 3; i++)
  924. {
  925. try
  926. {
  927. int b = in.read();
  928. // If end of stream, b is -1.
  929. if (b >= 0)
  930. {
  931. b3[i] = (byte) b;
  932. numBinaryBytes++;
  933. } // end if: not end of stream
  934. } // end try: read
  935. catch (java.io.IOException e)
  936. {
  937. // Only a problem if we got no data at all.
  938. if (i == 0)
  939. throw e;
  940. } // end catch
  941. } // end for: each needed input byte
  942. if (numBinaryBytes > 0)
  943. {
  944. encode3to4(b3, 0, numBinaryBytes, buffer, 0);
  945. position = 0;
  946. numSigBytes = 4;
  947. } // end if: got data
  948. else
  949. {
  950. return -1;
  951. } // end else
  952. } // end if: encoding
  953. // Else decoding
  954. else
  955. {
  956. byte[] b4 = new byte[4];
  957. int i = 0;
  958. for (i = 0; i < 4; i++)
  959. {
  960. // Read four "meaningful" bytes:
  961. int b = 0;
  962. do
  963. {
  964. b = in.read();
  965. }
  966. while (b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC);
  967. if (b < 0)
  968. break; // Reads a -1 if end of stream
  969. b4[i] = (byte) b;
  970. } // end for: each needed input byte
  971. if (i == 4)
  972. {
  973. numSigBytes = decode4to3(b4, 0, buffer, 0);
  974. position = 0;
  975. } // end if: got four characters
  976. else if (i == 0)
  977. {
  978. return -1;
  979. } // end else if: also padded correctly
  980. else
  981. {
  982. // Must have broken out from above.
  983. throw new java.io.IOException("Improperly padded Base64 input.");
  984. } // end
  985. } // end else: decode
  986. } // end else: get data
  987. // Got data?
  988. if (position >= 0)
  989. {
  990. // End of relevant data?
  991. if ( /* !encode && */position >= numSigBytes)
  992. return -1;
  993. if (encode && breakLines && lineLength >= MAX_LINE_LENGTH)
  994. {
  995. lineLength = 0;
  996. return '\n';
  997. } // end if
  998. lineLength++; // This isn't important when decoding
  999. // but throwing an extra "if" seems
  1000. // just as wasteful.
  1001. int b = buffer[position++];
  1002. if (position >= bufferLength)
  1003. position = -1;
  1004. return b & 0xFF; // This is how you "cast" a byte that's
  1005. // intended to be unsigned.
  1006. // end else
  1007. } // end if: position >= 0
  1008. // When JDK1.4 is more accepted, use an assertion here.
  1009. throw new java.io.IOException("Error in Base64 code reading stream.");
  1010. // end else
  1011. } // end read
  1012. /**
  1013. * Calls {@link #read} repeatedly until the end of stream is reached or
  1014. * <var>len</var> bytes are read. Returns number of bytes read into
  1015. * array or -1 if end of stream is encountered.
  1016. *
  1017. * @param dest
  1018. * array to hold values
  1019. * @param off
  1020. * offset for array
  1021. * @param len
  1022. * max number of bytes to read into array
  1023. * @return bytes read into array or -1 if end of stream is encountered.
  1024. * @since 1.3
  1025. */
  1026. @Override
  1027. public int read(byte[] dest, int off, int len) throws java.io.IOException
  1028. {
  1029. int i;
  1030. int b;
  1031. for (i = 0; i < len; i++)
  1032. {
  1033. b = read();
  1034. // if( b < 0 && i == 0 )
  1035. // return -1;
  1036. if (b >= 0)
  1037. dest[off + i] = (byte) b;
  1038. else if (i == 0)
  1039. return -1;
  1040. else
  1041. break; // Out of 'for' loop
  1042. } // end for: each byte read
  1043. return i;
  1044. } // end read
  1045. } // end inner class InputStream
  1046. /* I N N E R C L A S S O U T P U T S T R E A M */
  1047. /**
  1048. * A {@link Base64#OutputStream} will write data to another
  1049. * {@link java.io.OutputStream}, given in the constructor, and encode/decode
  1050. * to/from Base64 notation on the fly.
  1051. *
  1052. * @see Base64
  1053. * @see java.io.FilterOutputStream
  1054. * @since 1.3
  1055. */
  1056. public static class OutputStream extends java.io.FilterOutputStream
  1057. {
  1058. // private int options;
  1059. private boolean encode;
  1060. private int position;
  1061. private byte[] buffer;
  1062. private int bufferLength;
  1063. private int lineLength;
  1064. private boolean breakLines;
  1065. private byte[] b4; // Scratch used in a few places
  1066. private boolean suspendEncoding;
  1067. /**
  1068. * Constructs a {@link Base64#OutputStream} in ENCODE mode.
  1069. *
  1070. * @param out
  1071. * the {@link java.io.OutputStream} to which data will be
  1072. * written.
  1073. * @since 1.3
  1074. */
  1075. public OutputStream(java.io.OutputStream pOut)
  1076. {
  1077. this(pOut, ENCODE);
  1078. } // end constructor
  1079. /**
  1080. * Constructs a {@link Base64#OutputStream} in either ENCODE or DECODE
  1081. * mode.
  1082. * <p>
  1083. * Valid options:
  1084. *
  1085. * <pre>
  1086. * ENCODE or DECODE: Encode or Decode as data is read.
  1087. * DONT_BREAK_LINES: don't break lines at 76 characters
  1088. * (only meaningful when encoding)
  1089. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  1090. * </pre>
  1091. * <p>
  1092. * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
  1093. *
  1094. * @param out
  1095. * the {@link java.io.OutputStream} to which data will be
  1096. * written.
  1097. * @param options
  1098. * Specified options.
  1099. * @see Base64#ENCODE
  1100. * @see Base64#DECODE
  1101. * @see Base64#DONT_BREAK_LINES
  1102. * @since 1.3
  1103. */
  1104. public OutputStream(java.io.OutputStream pOut, int options)
  1105. {
  1106. super(pOut);
  1107. // this.options = options;
  1108. breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
  1109. encode = (options & ENCODE) == ENCODE;
  1110. bufferLength = encode ? 3 : 4;
  1111. buffer = new byte[bufferLength];
  1112. position = 0;
  1113. lineLength = 0;
  1114. suspendEncoding = false;
  1115. b4 = new byte[4];
  1116. } // end constructor
  1117. /**
  1118. * Writes the byte to the output stream after converting to/from Base64
  1119. * notation. When encoding, bytes are buffered three at a time before
  1120. * the output stream actually gets a write() call. When decoding, bytes
  1121. * are buffered four at a time.
  1122. *
  1123. * @param theByte
  1124. * the byte to write
  1125. * @since 1.3
  1126. */
  1127. @Override
  1128. public void write(int theByte) throws java.io.IOException
  1129. {
  1130. // Encoding suspended?
  1131. if (suspendEncoding)
  1132. {
  1133. super.out.write(theByte);
  1134. return;
  1135. } // end if: supsended
  1136. // Encode?
  1137. if (encode)
  1138. {
  1139. buffer[position++] = (byte) theByte;
  1140. if (position >= bufferLength) // Enough to encode.
  1141. {
  1142. out.write(encode3to4(b4, buffer, bufferLength));
  1143. lineLength += 4;
  1144. if (breakLines && lineLength >= MAX_LINE_LENGTH)
  1145. {
  1146. out.write(NEW_LINE);
  1147. lineLength = 0;
  1148. } // end if: end of line
  1149. position = 0;
  1150. } // end if: enough to output
  1151. } // end if: encoding
  1152. // Else, Decoding
  1153. else
  1154. {
  1155. // Meaningful Base64 character?
  1156. if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC)
  1157. {
  1158. buffer[position++] = (byte) theByte;
  1159. if (position >= bufferLength) // Enough to output.
  1160. {
  1161. int len = Base64.decode4to3(buffer, 0, b4, 0);
  1162. out.write(b4, 0, len);
  1163. // out.write( Base64.decode4to3( buffer ) );
  1164. position = 0;
  1165. } // end if: enough to output
  1166. } // end if: meaningful base64 character
  1167. else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC)
  1168. {
  1169. throw new java.io.IOException("Invalid character in Base64 data.");
  1170. } // end else: not white space either
  1171. } // end else: decoding
  1172. } // end write
  1173. /**
  1174. * Calls {@link #write} repeatedly until <var>len</var> bytes are
  1175. * written.
  1176. *
  1177. * @param theBytes
  1178. * array from which to read bytes
  1179. * @param off
  1180. * offset for array
  1181. * @param len
  1182. * max number of bytes to read into array
  1183. * @since 1.3
  1184. */
  1185. @Override
  1186. public void write(byte[] theBytes, int off, int len) throws java.io.IOException
  1187. {
  1188. // Encoding suspended?
  1189. if (suspendEncoding)
  1190. {
  1191. super.out.write(theBytes, off, len);
  1192. return;
  1193. } // end if: supsended
  1194. for (int i = 0; i < len; i++)
  1195. {
  1196. write(theBytes[off + i]);
  1197. } // end for: each byte written
  1198. } // end write
  1199. /**
  1200. * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer
  1201. * without closing the stream.
  1202. */
  1203. public void flushBase64() throws java.io.IOException
  1204. {
  1205. if (position > 0)
  1206. {
  1207. if (encode)
  1208. {
  1209. out.write(encode3to4(b4, buffer, position));
  1210. position = 0;
  1211. } // end if: encoding
  1212. else
  1213. {
  1214. throw new java.io.IOException("Base64 input not properly padded.");
  1215. } // end else: decoding
  1216. } // end if: buffer partially full
  1217. } // end flush
  1218. /**
  1219. * Flushes and closes (I think, in the superclass) the stream.
  1220. *
  1221. * @since 1.3
  1222. */
  1223. @Override
  1224. public void close() throws java.io.IOException
  1225. {
  1226. // 1. Ensure that pending characters are written
  1227. flushBase64();
  1228. // 2. Actually close the stream
  1229. // Base class both flushes and closes.
  1230. super.close();
  1231. buffer = null;
  1232. out = null;
  1233. } // end close
  1234. /**
  1235. * Suspends encoding of the stream. May be helpful if you need to embed
  1236. * a piece of base640-encoded data in a stream.
  1237. *
  1238. * @since 1.5.1
  1239. */
  1240. public void suspendEncoding() throws java.io.IOException
  1241. {
  1242. flushBase64();
  1243. suspendEncoding = true;
  1244. } // end suspendEncoding
  1245. /**
  1246. * Resumes encoding of the stream. May be helpful if you need to embed a
  1247. * piece of base640-encoded data in a stream.
  1248. *
  1249. * @since 1.5.1
  1250. */
  1251. public void resumeEncoding()
  1252. {
  1253. suspendEncoding = false;
  1254. } // end resumeEncoding
  1255. } // end inner class OutputStream
  1256. } // end class Base64