Base64.java 40 KB

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