Base64.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. ObjectOutputStream oos = new ObjectOutputStream((gzip == GZIP) ? new GZIPOutputStream(b64os) : b64os))
  319. {
  320. oos.writeObject(serializableObject);
  321. value = baos.toByteArray();
  322. }
  323. catch (IOException e)
  324. {
  325. e.printStackTrace();
  326. return null;
  327. }
  328. // Return value according to relevant encoding.
  329. if (value != null)
  330. {
  331. try
  332. {
  333. return new String(value, PREFERRED_ENCODING);
  334. }
  335. catch (UnsupportedEncodingException uue)
  336. {
  337. return new String(value);
  338. }
  339. }
  340. return null;
  341. }
  342. /**
  343. * Encodes a byte array into Base64 notation. Does not GZip-compress data.
  344. *
  345. * @param source
  346. * The data to convert
  347. * @return
  348. * @since 1.4
  349. */
  350. public static String encodeBytes(byte[] source)
  351. {
  352. return encodeBytes(source, 0, source.length, NO_OPTIONS);
  353. }
  354. /**
  355. * Encodes a byte array into Base64 notation.
  356. * <p>
  357. * Valid options:
  358. *
  359. * <pre>
  360. * GZIP: gzip-compresses object before encoding it.
  361. * DONT_BREAK_LINES: don't break lines at 76 characters
  362. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  363. * </pre>
  364. * <p>
  365. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  366. * <p>
  367. * Example:
  368. * <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  369. *
  370. *
  371. * @param source
  372. * The data to convert
  373. * @param options
  374. * Specified options
  375. * @return
  376. * @see Base64#GZIP
  377. * @see Base64#DONT_BREAK_LINES
  378. * @since 2.0
  379. */
  380. public static String encodeBytes(byte[] source, int options)
  381. {
  382. return encodeBytes(source, 0, source.length, options);
  383. }
  384. /**
  385. * Encodes a byte array into Base64 notation. Does not GZip-compress data.
  386. *
  387. * @param source
  388. * The data to convert
  389. * @param off
  390. * Offset in array where conversion should begin
  391. * @param len
  392. * Length of data to convert
  393. * @return
  394. * @since 1.4
  395. */
  396. public static String encodeBytes(byte[] source, int off, int len)
  397. {
  398. return encodeBytes(source, off, len, NO_OPTIONS);
  399. }
  400. /**
  401. * Encodes a byte array into Base64 notation.
  402. * <p>
  403. * Valid options:
  404. *
  405. * <pre>
  406. * GZIP: gzip-compresses object before encoding it.
  407. * DONT_BREAK_LINES: don't break lines at 76 characters
  408. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  409. * </pre>
  410. * <p>
  411. * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
  412. * <p>
  413. * Example:
  414. * <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
  415. *
  416. *
  417. * @param source
  418. * The data to convert
  419. * @param off
  420. * Offset in array where conversion should begin
  421. * @param len
  422. * Length of data to convert
  423. * @param options
  424. * Specified options
  425. * @return
  426. * @see Base64#GZIP
  427. * @see Base64#DONT_BREAK_LINES
  428. * @since 2.0
  429. */
  430. public static String encodeBytes(byte[] source, int off, int len, int options)
  431. {
  432. // Isolate options
  433. int dontBreakLines = (options & DONT_BREAK_LINES);
  434. int gzip = (options & GZIP);
  435. // Compress?
  436. if (gzip == GZIP)
  437. {
  438. // GZip -> Base64 -> ByteArray
  439. byte[] value = null;
  440. try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
  441. Base64.OutputStream b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);
  442. GZIPOutputStream gzos = new GZIPOutputStream(b64os))
  443. {
  444. gzos.write(source, off, len);
  445. value = baos.toByteArray();
  446. }
  447. catch (IOException e)
  448. {
  449. _log.warning("Base64: " + e.getMessage());
  450. return null;
  451. }
  452. // Return value according to relevant encoding.
  453. if (value != null)
  454. {
  455. try
  456. {
  457. return new String(value, PREFERRED_ENCODING);
  458. }
  459. catch (UnsupportedEncodingException uue)
  460. {
  461. return new String(value);
  462. }
  463. }
  464. }
  465. // Convert option to boolean in way that code likes it.
  466. boolean breakLines = dontBreakLines == 0;
  467. int len43 = len * 4 / 3;
  468. byte[] outBuff = new byte[(len43) // Main 4:3
  469. + ((len % 3) > 0 ? 4 : 0) // Account for padding
  470. + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines
  471. int d = 0;
  472. int e = 0;
  473. int len2 = len - 2;
  474. int lineLength = 0;
  475. for (; d < len2; d += 3, e += 4)
  476. {
  477. encode3to4(source, d + off, 3, outBuff, e);
  478. lineLength += 4;
  479. if (breakLines && lineLength == MAX_LINE_LENGTH)
  480. {
  481. outBuff[e + 4] = NEW_LINE;
  482. e++;
  483. lineLength = 0;
  484. }
  485. } // en dfor: each piece of array
  486. if (d < len)
  487. {
  488. encode3to4(source, d + off, len - d, outBuff, e);
  489. e += 4;
  490. }
  491. // Return value according to relevant encoding.
  492. try
  493. {
  494. return new String(outBuff, 0, e, PREFERRED_ENCODING);
  495. }
  496. catch (UnsupportedEncodingException uue)
  497. {
  498. return new String(outBuff, 0, e);
  499. }
  500. }
  501. /* D E C O D I N G M E T H O D S */
  502. // /**
  503. // * Decodes the first four bytes of array <var>fourBytes</var>
  504. // * and returns an array up to three bytes long with the
  505. // * decoded values.
  506. // *
  507. // * @param fourBytes the array with Base64 content
  508. // * @return array with decoded values
  509. // * @since 1.3
  510. // */
  511. // private static byte[] decode4to3( byte[] fourBytes )
  512. // {
  513. // byte[] outBuff1 = new byte[3];
  514. // int count = decode4to3( fourBytes, 0, outBuff1, 0 );
  515. // byte[] outBuff2 = new byte[ count ];
  516. //
  517. // for( int i = 0; i < count; i++ )
  518. // outBuff2[i] = outBuff1[i];
  519. //
  520. // return outBuff2;
  521. // }
  522. /**
  523. * Decodes four bytes from array <var>source</var> and writes the resulting
  524. * bytes (up to three of them) to <var>destination</var>. The source and
  525. * destination arrays can be manipulated anywhere along their length by
  526. * specifying <var>srcOffset</var> and <var>destOffset</var>. This method
  527. * does not check to make sure your arrays are large enough to accomodate
  528. * <var>srcOffset</var> + 4 for the <var>source</var> array or
  529. * <var>destOffset</var> + 3 for the <var>destination</var> array. This
  530. * method returns the actual number of bytes that were converted from the
  531. * Base64 encoding.
  532. *
  533. *
  534. * @param source
  535. * the array to convert
  536. * @param srcOffset
  537. * the index where conversion begins
  538. * @param destination
  539. * the array to hold the conversion
  540. * @param destOffset
  541. * the index where output will be put
  542. * @return the number of decoded bytes converted
  543. * @since 1.3
  544. */
  545. static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset)
  546. {
  547. // Example: Dk==
  548. if (source[srcOffset + 2] == EQUALS_SIGN)
  549. {
  550. // Two ways to do the same thing. Don't know which way I like best.
  551. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
  552. // )
  553. // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
  554. int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
  555. | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
  556. destination[destOffset] = (byte) (outBuff >>> 16);
  557. return 1;
  558. }
  559. // Example: DkL=
  560. else if (source[srcOffset + 3] == EQUALS_SIGN)
  561. {
  562. // Two ways to do the same thing. Don't know which way I like best.
  563. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
  564. // )
  565. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  566. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
  567. int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
  568. | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
  569. | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
  570. destination[destOffset] = (byte) (outBuff >>> 16);
  571. destination[destOffset + 1] = (byte) (outBuff >>> 8);
  572. return 2;
  573. }
  574. // Example: DkLE
  575. else
  576. {
  577. try
  578. {
  579. // Two ways to do the same thing. Don't know which way I like
  580. // best.
  581. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 )
  582. // >>> 6 )
  583. // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
  584. // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
  585. // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
  586. int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
  587. | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
  588. | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
  589. | ((DECODABET[source[srcOffset + 3]] & 0xFF));
  590. destination[destOffset] = (byte) (outBuff >> 16);
  591. destination[destOffset + 1] = (byte) (outBuff >> 8);
  592. destination[destOffset + 2] = (byte) (outBuff);
  593. return 3;
  594. }
  595. catch (Exception e)
  596. {
  597. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset]), ": ", String.valueOf(DECODABET[source[srcOffset]])));
  598. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset + 1]), ": ", String.valueOf(DECODABET[source[srcOffset + 1]])));
  599. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset + 2]), ": ", String.valueOf(DECODABET[source[srcOffset + 2]])));
  600. System.out.println(StringUtil.concat(String.valueOf(source[srcOffset + 3]), ": ", String.valueOf(DECODABET[source[srcOffset + 3]])));
  601. return -1;
  602. }
  603. }
  604. }
  605. /**
  606. * Very low-level access to decoding ASCII characters in the form of a byte
  607. * array. Does not support automatically gunzipping or any other "fancy"
  608. * features.
  609. *
  610. * @param source
  611. * The Base64 encoded data
  612. * @param off
  613. * The offset of where to begin decoding
  614. * @param len
  615. * The length of characters to decode
  616. * @return decoded data
  617. * @since 1.3
  618. */
  619. public static byte[] decode(byte[] source, int off, int len)
  620. {
  621. int len34 = len * 3 / 4;
  622. byte[] outBuff = new byte[len34]; // Upper limit on size of output
  623. int outBuffPosn = 0;
  624. byte[] b4 = new byte[4];
  625. int b4Posn = 0;
  626. int i = 0;
  627. byte sbiCrop = 0;
  628. byte sbiDecode = 0;
  629. for (i = off; i < off + len; i++)
  630. {
  631. sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
  632. sbiDecode = DECODABET[sbiCrop];
  633. if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better
  634. {
  635. if (sbiDecode >= EQUALS_SIGN_ENC)
  636. {
  637. b4[b4Posn++] = sbiCrop;
  638. if (b4Posn > 3)
  639. {
  640. outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
  641. b4Posn = 0;
  642. // If that was the equals sign, break out of 'for' loop
  643. if (sbiCrop == EQUALS_SIGN)
  644. break;
  645. } // end if: quartet built
  646. } // end if: equals sign or better
  647. } // end if: white space, equals sign or better
  648. else
  649. {
  650. System.err.println(StringUtil.concat("Bad Base64 input character at ", String.valueOf(i), ": ", String.valueOf(source[i]), "(decimal)"));
  651. return null;
  652. }
  653. }
  654. byte[] out = new byte[outBuffPosn];
  655. System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
  656. return out;
  657. }
  658. /**
  659. * Decodes data from Base64 notation, automatically detecting
  660. * gzip-compressed data and decompressing it.
  661. *
  662. * @param s
  663. * the string to decode
  664. * @return the decoded data
  665. * @since 1.4
  666. */
  667. public static byte[] decode(String s)
  668. {
  669. byte[] bytes;
  670. try
  671. {
  672. bytes = s.getBytes(PREFERRED_ENCODING);
  673. }
  674. catch (UnsupportedEncodingException uee)
  675. {
  676. bytes = s.getBytes();
  677. }
  678. // Decode
  679. bytes = decode(bytes, 0, bytes.length);
  680. // Check to see if it's gzip-compressed
  681. // GZIP Magic Two-Byte Number: 0x8b1f (35615)
  682. // In case decoding returned null
  683. if ((bytes != null) && (bytes.length >= 2))
  684. {
  685. final int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
  686. // Don't want to get ArrayIndexOutOfBounds exception
  687. if (bytes.length >= 4 && GZIPInputStream.GZIP_MAGIC == head)
  688. {
  689. byte[] buffer = new byte[2048];
  690. int length = 0;
  691. try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
  692. GZIPInputStream gzis = new GZIPInputStream(bais);
  693. ByteArrayOutputStream baos = new ByteArrayOutputStream())
  694. {
  695. while ((length = gzis.read(buffer)) >= 0)
  696. {
  697. baos.write(buffer, 0, length);
  698. }
  699. // No error? Get new bytes.
  700. bytes = baos.toByteArray();
  701. }
  702. catch (IOException e)
  703. {
  704. // Just return originally-decoded bytes
  705. }
  706. }
  707. }
  708. return bytes;
  709. }
  710. /**
  711. * Attempts to decode Base64 data and deserialize a Java Object within.
  712. * Returns <tt>null</tt> if there was an error.
  713. *
  714. * @param encodedObject
  715. * The Base64 data to decode
  716. * @return The decoded and deserialized object
  717. * @since 1.5
  718. */
  719. public static Object decodeToObject(String encodedObject)
  720. {
  721. // Decode and gunzip if necessary
  722. byte[] objBytes = decode(encodedObject);
  723. Object obj = null;
  724. try (ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
  725. ObjectInputStream ois = new ObjectInputStream(bais))
  726. {
  727. obj = ois.readObject();
  728. }
  729. catch (IOException e)
  730. {
  731. _log.warning("Base64: " + e.getMessage());
  732. }
  733. catch (ClassNotFoundException e)
  734. {
  735. _log.warning("Base64: " + e.getMessage());
  736. }
  737. return obj;
  738. }
  739. /* I N N E R C L A S S I N P U T S T R E A M */
  740. /**
  741. * A {@link #InputStream} will read data from another
  742. * {@link java.io.InputStream}, given in the constructor, and encode/decode
  743. * to/from Base64 notation on the fly.
  744. *
  745. * @see Base64
  746. * @see java.io.FilterInputStream
  747. * @since 1.3
  748. */
  749. public static class InputStream extends FilterInputStream
  750. {
  751. // private int options; // Options specified
  752. private boolean encode; // Encoding or decoding
  753. private int position; // Current position in the buffer
  754. private byte[] buffer; // Small buffer holding converted data
  755. private int bufferLength; // Length of buffer (3 or 4)
  756. private int numSigBytes; // Number of meaningful bytes in the buffer
  757. private int lineLength;
  758. private boolean breakLines; // Break lines at less than 80 characters
  759. /**
  760. * Constructs a {@link #InputStream} in DECODE mode.
  761. *
  762. * @param pIn
  763. * the {@link java.io.InputStream} from which to read data.
  764. * @since 1.3
  765. */
  766. public InputStream(java.io.InputStream pIn)
  767. {
  768. this(pIn, DECODE);
  769. }
  770. /**
  771. * Constructs a {@link #InputStream} in either ENCODE or DECODE
  772. * mode.
  773. * <p>
  774. * Valid options:
  775. *
  776. * <pre>
  777. * ENCODE or DECODE: Encode or Decode as data is read.
  778. * DONT_BREAK_LINES: don't break lines at 76 characters
  779. * (only meaningful when encoding)
  780. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  781. * </pre>
  782. * <p>
  783. * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
  784. *
  785. *
  786. * @param pIn
  787. * the {@link java.io.InputStream} from which to read data.
  788. * @param options
  789. * Specified options
  790. * @see Base64#ENCODE
  791. * @see Base64#DECODE
  792. * @see Base64#DONT_BREAK_LINES
  793. * @since 2.0
  794. */
  795. public InputStream(java.io.InputStream pIn, int options)
  796. {
  797. super(pIn);
  798. // this.options = options;
  799. breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
  800. encode = (options & ENCODE) == ENCODE;
  801. bufferLength = encode ? 4 : 3;
  802. buffer = new byte[bufferLength];
  803. position = -1;
  804. lineLength = 0;
  805. }
  806. /**
  807. * Reads enough of the input stream to convert to/from Base64 and
  808. * returns the next byte.
  809. *
  810. * @return next byte
  811. * @since 1.3
  812. */
  813. @Override
  814. public int read() throws IOException
  815. {
  816. // Do we need to get data?
  817. if (position < 0)
  818. {
  819. if (encode)
  820. {
  821. byte[] b3 = new byte[3];
  822. int numBinaryBytes = 0;
  823. for (int i = 0; i < 3; i++)
  824. {
  825. try
  826. {
  827. int b = in.read();
  828. // If end of stream, b is -1.
  829. if (b >= 0)
  830. {
  831. b3[i] = (byte) b;
  832. numBinaryBytes++;
  833. }
  834. }
  835. catch (IOException e)
  836. {
  837. // Only a problem if we got no data at all.
  838. if (i == 0)
  839. throw e;
  840. }
  841. }
  842. if (numBinaryBytes > 0)
  843. {
  844. encode3to4(b3, 0, numBinaryBytes, buffer, 0);
  845. position = 0;
  846. numSigBytes = 4;
  847. }
  848. else
  849. {
  850. return -1;
  851. }
  852. }
  853. else
  854. {
  855. byte[] b4 = new byte[4];
  856. int i = 0;
  857. for (i = 0; i < 4; i++)
  858. {
  859. // Read four "meaningful" bytes:
  860. int b = 0;
  861. do
  862. {
  863. b = in.read();
  864. }
  865. while (b >= 0 && DECODABET[b & 0x7f] <= WHITE_SPACE_ENC);
  866. if (b < 0)
  867. break; // Reads a -1 if end of stream
  868. b4[i] = (byte) b;
  869. } // end for: each needed input byte
  870. if (i == 4)
  871. {
  872. numSigBytes = decode4to3(b4, 0, buffer, 0);
  873. position = 0;
  874. } // end if: got four characters
  875. else if (i == 0)
  876. {
  877. return -1;
  878. } // end else if: also padded correctly
  879. else
  880. {
  881. // Must have broken out from above.
  882. throw new IOException("Improperly padded Base64 input.");
  883. }
  884. }
  885. }
  886. // Got data?
  887. if (position >= 0)
  888. {
  889. // End of relevant data?
  890. if ( /* !encode && */position >= numSigBytes)
  891. return -1;
  892. if (encode && breakLines && lineLength >= MAX_LINE_LENGTH)
  893. {
  894. lineLength = 0;
  895. return '\n';
  896. }
  897. // This isn't important when decoding but throwing an extra "if" seems just as wasteful.
  898. lineLength++;
  899. int b = buffer[position++];
  900. if (position >= bufferLength)
  901. position = -1;
  902. // This is how you "cast" a byte that's intended to be unsigned.
  903. return b & 0xFF;
  904. }
  905. // When JDK1.4 is more accepted, use an assertion here.
  906. throw new IOException("Error in Base64 code reading stream.");
  907. }
  908. /**
  909. * Calls {@link #read} repeatedly until the end of stream is reached or
  910. * <var>len</var> bytes are read. Returns number of bytes read into
  911. * array or -1 if end of stream is encountered.
  912. *
  913. * @param dest
  914. * array to hold values
  915. * @param off
  916. * offset for array
  917. * @param len
  918. * max number of bytes to read into array
  919. * @return bytes read into array or -1 if end of stream is encountered.
  920. * @since 1.3
  921. */
  922. @Override
  923. public int read(byte[] dest, int off, int len) throws IOException
  924. {
  925. int i;
  926. int b;
  927. for (i = 0; i < len; i++)
  928. {
  929. b = read();
  930. // if( b < 0 && i == 0 )
  931. // return -1;
  932. if (b >= 0)
  933. dest[off + i] = (byte) b;
  934. else if (i == 0)
  935. return -1;
  936. else
  937. break;
  938. }
  939. return i;
  940. }
  941. }
  942. /* I N N E R C L A S S O U T P U T S T R E A M */
  943. /**
  944. * A {@link #OutputStream} will write data to another
  945. * {@link java.io.OutputStream}, given in the constructor, and encode/decode
  946. * to/from Base64 notation on the fly.
  947. *
  948. * @see Base64
  949. * @see java.io.FilterOutputStream
  950. * @since 1.3
  951. */
  952. public static class OutputStream extends FilterOutputStream
  953. {
  954. // private int options;
  955. private boolean encode;
  956. private int position;
  957. private byte[] buffer;
  958. private int bufferLength;
  959. private int lineLength;
  960. private boolean breakLines;
  961. private byte[] b4; // Scratch used in a few places
  962. private boolean suspendEncoding;
  963. /**
  964. * Constructs a {@link #OutputStream} in ENCODE mode.
  965. *
  966. * @param pOut
  967. * the {@link java.io.OutputStream} to which data will be
  968. * written.
  969. * @since 1.3
  970. */
  971. public OutputStream(java.io.OutputStream pOut)
  972. {
  973. this(pOut, ENCODE);
  974. }
  975. /**
  976. * Constructs a {@link #OutputStream} in either ENCODE or DECODE
  977. * mode.
  978. * <p>
  979. * Valid options:
  980. *
  981. * <pre>
  982. * ENCODE or DECODE: Encode or Decode as data is read.
  983. * DONT_BREAK_LINES: don't break lines at 76 characters
  984. * (only meaningful when encoding)
  985. * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
  986. * </pre>
  987. * <p>
  988. * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
  989. *
  990. * @param pOut
  991. * the {@link java.io.OutputStream} to which data will be
  992. * written.
  993. * @param options
  994. * Specified options.
  995. * @see Base64#ENCODE
  996. * @see Base64#DECODE
  997. * @see Base64#DONT_BREAK_LINES
  998. * @since 1.3
  999. */
  1000. public OutputStream(java.io.OutputStream pOut, int options)
  1001. {
  1002. super(pOut);
  1003. // this.options = options;
  1004. breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
  1005. encode = (options & ENCODE) == ENCODE;
  1006. bufferLength = encode ? 3 : 4;
  1007. buffer = new byte[bufferLength];
  1008. position = 0;
  1009. lineLength = 0;
  1010. suspendEncoding = false;
  1011. b4 = new byte[4];
  1012. }
  1013. /**
  1014. * Writes the byte to the output stream after converting to/from Base64
  1015. * notation. When encoding, bytes are buffered three at a time before
  1016. * the output stream actually gets a write() call. When decoding, bytes
  1017. * are buffered four at a time.
  1018. *
  1019. * @param theByte
  1020. * the byte to write
  1021. * @since 1.3
  1022. */
  1023. @Override
  1024. public void write(int theByte) throws IOException
  1025. {
  1026. // Encoding suspended?
  1027. if (suspendEncoding)
  1028. {
  1029. super.out.write(theByte);
  1030. return;
  1031. }
  1032. // Encode?
  1033. if (encode)
  1034. {
  1035. buffer[position++] = (byte) theByte;
  1036. if (position >= bufferLength) // Enough to encode.
  1037. {
  1038. out.write(encode3to4(b4, buffer, bufferLength));
  1039. lineLength += 4;
  1040. if (breakLines && lineLength >= MAX_LINE_LENGTH)
  1041. {
  1042. out.write(NEW_LINE);
  1043. lineLength = 0;
  1044. }
  1045. position = 0;
  1046. }
  1047. }
  1048. else
  1049. {
  1050. // Meaningful Base64 character?
  1051. if (DECODABET[theByte & 0x7f] > WHITE_SPACE_ENC)
  1052. {
  1053. buffer[position++] = (byte) theByte;
  1054. if (position >= bufferLength) // Enough to output.
  1055. {
  1056. int len = Base64.decode4to3(buffer, 0, b4, 0);
  1057. out.write(b4, 0, len);
  1058. // out.write( Base64.decode4to3( buffer ) );
  1059. position = 0;
  1060. }
  1061. }
  1062. else if (DECODABET[theByte & 0x7f] != WHITE_SPACE_ENC)
  1063. {
  1064. throw new IOException("Invalid character in Base64 data.");
  1065. }
  1066. }
  1067. }
  1068. /**
  1069. * Calls {@link #write} repeatedly until <var>len</var> bytes are
  1070. * written.
  1071. *
  1072. * @param theBytes
  1073. * array from which to read bytes
  1074. * @param off
  1075. * offset for array
  1076. * @param len
  1077. * max number of bytes to read into array
  1078. * @since 1.3
  1079. */
  1080. @Override
  1081. public void write(byte[] theBytes, int off, int len) throws IOException
  1082. {
  1083. // Encoding suspended?
  1084. if (suspendEncoding)
  1085. {
  1086. super.out.write(theBytes, off, len);
  1087. return;
  1088. }
  1089. for (int i = 0; i < len; i++)
  1090. {
  1091. write(theBytes[off + i]);
  1092. }
  1093. }
  1094. /**
  1095. * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer
  1096. * without closing the stream.
  1097. * @throws IOException
  1098. */
  1099. public void flushBase64() throws IOException
  1100. {
  1101. if (position > 0)
  1102. {
  1103. if (encode)
  1104. {
  1105. out.write(encode3to4(b4, buffer, position));
  1106. position = 0;
  1107. }
  1108. else
  1109. {
  1110. throw new IOException("Base64 input not properly padded.");
  1111. }
  1112. }
  1113. }
  1114. /**
  1115. * Flushes and closes (I think, in the superclass) the stream.
  1116. *
  1117. * @since 1.3
  1118. */
  1119. @Override
  1120. public void close() throws IOException
  1121. {
  1122. // 1. Ensure that pending characters are written
  1123. flushBase64();
  1124. // 2. Actually close the stream
  1125. // Base class both flushes and closes.
  1126. super.close();
  1127. buffer = null;
  1128. out = null;
  1129. }
  1130. /**
  1131. * Suspends encoding of the stream. May be helpful if you need to embed
  1132. * a piece of base640-encoded data in a stream.
  1133. * @throws IOException
  1134. *
  1135. * @since 1.5.1
  1136. */
  1137. public void suspendEncoding() throws IOException
  1138. {
  1139. flushBase64();
  1140. suspendEncoding = true;
  1141. }
  1142. /**
  1143. * Resumes encoding of the stream. May be helpful if you need to embed a
  1144. * piece of base640-encoded data in a stream.
  1145. *
  1146. * @since 1.5.1
  1147. */
  1148. public void resumeEncoding()
  1149. {
  1150. suspendEncoding = false;
  1151. }
  1152. }
  1153. }