Base64.java 37 KB

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