Base64.java 37 KB

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