Base64.java 35 KB

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