Base64.java 34 KB

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