Base64.java 40 KB

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