PageRenderTime 52ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/configJava/src/main/java/uk/co/bigbeeconsultants/bconfig/io/Base64.java

https://bitbucket.org/rickb777/bee-config
Java | 702 lines | 304 code | 92 blank | 306 comment | 116 complexity | c08e09d115e779c594bd5c7eefa90f56 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause
  1. package uk.co.bigbeeconsultants.bconfig.io;
  2. import java.util.Arrays;
  3. import static java.nio.charset.StandardCharsets.UTF_8;
  4. /**
  5. * A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance
  6. * with RFC 2045.<br><br>
  7. * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster
  8. * on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes)
  9. * compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br>
  10. * <p/>
  11. * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and
  12. * about 50% faster for decoding large arrays. This implementation is about twice as fast on very small
  13. * arrays (&lt 30 bytes). If source/destination is a <code>String</code> this
  14. * version is about three times as fast due to the fact that the Commons Codec result has to be recoded
  15. * to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br>
  16. * <p/>
  17. * This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only
  18. * allocates the resulting array. This produces less garbage and it is possible to handle arrays twice
  19. * as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown
  20. * whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance
  21. * is quite low it probably does.<br><br>
  22. * <p/>
  23. * The encoder produces the same output as the Sun one except that the Sun's encoder appends
  24. * a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the
  25. * length and is probably a side effect. Both are in conformance with RFC 2045 though.<br>
  26. * Commons codec seem to always add a trailing line separator.<br><br>
  27. * <p/>
  28. * <b>Note!</b>
  29. * The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
  30. * thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different
  31. * format types. The methods not used can simply be commented out.<br><br>
  32. * <p/>
  33. * There is also a "fast" version of all decode methods that works the same way as the normal ones, but
  34. * har a few demands on the decoded input. Normally though, these fast versions should be used if the source if
  35. * the input is known and it hasn't bee tampered with.<br><br>
  36. * <p/>
  37. * If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com.
  38. * <p/>
  39. * Origin: http://migbase64.sourceforge.net/
  40. * <p/>
  41. * Licence (BSD):
  42. * ==============
  43. * <p/>
  44. * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)
  45. * All rights reserved.
  46. * <p/>
  47. * Redistribution and use in source and binary forms, with or without modification,
  48. * are permitted provided that the following conditions are met:
  49. * Redistributions of source code must retain the above copyright notice, this list
  50. * of conditions and the following disclaimer.
  51. * Redistributions in binary form must reproduce the above copyright notice, this
  52. * list of conditions and the following disclaimer in the documentation and/or other
  53. * materials provided with the distribution.
  54. * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
  55. * used to endorse or promote products derived from this software without specific
  56. * prior written permission.
  57. * <p/>
  58. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  59. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  60. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  61. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  62. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  63. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  64. * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  65. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  66. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  67. * OF SUCH DAMAGE.
  68. *
  69. * @author Mikael Grev
  70. * Date: 2004-aug-02
  71. * Time: 11:31:11
  72. * @version 2.2
  73. */
  74. public final class Base64 {
  75. private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  76. private static final int[] IA = new int[256];
  77. static {
  78. Arrays.fill(IA, -1);
  79. for (int i = 0, iS = CA.length; i < iS; i++)
  80. IA[CA[i]] = i;
  81. IA['='] = 0;
  82. }
  83. // ****************************************************************************************
  84. // * char[] version
  85. // ****************************************************************************************
  86. /**
  87. * Encodes a raw byte array into a BASE64 <code>char[]</code> representation in accordance with RFC 2045.
  88. *
  89. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  90. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  91. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  92. * little faster.
  93. * @return A BASE64 encoded array. Never <code>null</code>.
  94. */
  95. public static char[] encodeToChars(byte[] sArr, boolean lineSep) {
  96. // Check special case
  97. int sLen = sArr != null ? sArr.length : 0;
  98. if (sLen == 0)
  99. return new char[0];
  100. int eLen = (sLen / 3) * 3; // Length of even 24-bits.
  101. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
  102. int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
  103. char[] dArr = new char[dLen];
  104. // Encode even 24-bits
  105. for (int s = 0, d = 0, cc = 0; s < eLen; ) {
  106. // Copy next three bytes into lower 24 bits of int, paying attension to sign.
  107. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
  108. // Encode the int into four chars
  109. dArr[d++] = CA[(i >>> 18) & 0x3f];
  110. dArr[d++] = CA[(i >>> 12) & 0x3f];
  111. dArr[d++] = CA[(i >>> 6) & 0x3f];
  112. dArr[d++] = CA[i & 0x3f];
  113. // Add optional line separator
  114. if (lineSep && ++cc == 19 && d < dLen - 2) {
  115. dArr[d++] = '\r';
  116. dArr[d++] = '\n';
  117. cc = 0;
  118. }
  119. }
  120. // Pad and encode last bits if source isn't even 24 bits.
  121. int left = sLen - eLen; // 0 - 2.
  122. if (left > 0) {
  123. // Prepare the int
  124. int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
  125. // Set last four chars
  126. dArr[dLen - 4] = CA[i >> 12];
  127. dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
  128. dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
  129. dArr[dLen - 1] = '=';
  130. }
  131. return dArr;
  132. }
  133. /**
  134. * Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle arrays both with
  135. * and without line separators.
  136. *
  137. * @param sArr The source array. <code>null</code> or length 0 will return an empty array.
  138. * @return The decoded UTF8 string. May be of length 0. Will be <code>null</code> if the legal characters
  139. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  140. */
  141. public static String decodeToString(byte[] sArr) {
  142. return new String(decode(sArr), UTF_8);
  143. }
  144. /**
  145. * Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle arrays both with
  146. * and without line separators.
  147. *
  148. * @param sArr The source array. <code>null</code> or length 0 will return an empty array.
  149. * @return The decoded UTF8 string. May be of length 0. Will be <code>null</code> if the legal characters
  150. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  151. */
  152. public static String decodeToString(char[] sArr) {
  153. return new String(decode(sArr), UTF_8);
  154. }
  155. /**
  156. * Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle arrays both with
  157. * and without line separators.
  158. *
  159. * @param sArr The source array. <code>null</code> or length 0 will return an empty array.
  160. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  161. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  162. */
  163. public static byte[] decode(char[] sArr) {
  164. // Check special case
  165. int sLen = sArr != null ? sArr.length : 0;
  166. if (sLen == 0)
  167. return new byte[0];
  168. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  169. // so we don't have to reallocate & copy it later.
  170. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  171. for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
  172. if (IA[sArr[i]] < 0)
  173. sepCnt++;
  174. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  175. if ((sLen - sepCnt) % 4 != 0)
  176. return null;
  177. int pad = 0;
  178. for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0; )
  179. if (sArr[i] == '=')
  180. pad++;
  181. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  182. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  183. for (int s = 0, d = 0; d < len; ) {
  184. // Assemble three bytes into an int from four "valid" characters.
  185. int i = 0;
  186. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  187. int c = IA[sArr[s++]];
  188. if (c >= 0)
  189. i |= c << (18 - j * 6);
  190. else
  191. j--;
  192. }
  193. // Add the bytes
  194. dArr[d++] = (byte) (i >> 16);
  195. if (d < len) {
  196. dArr[d++] = (byte) (i >> 8);
  197. if (d < len)
  198. dArr[d++] = (byte) i;
  199. }
  200. }
  201. return dArr;
  202. }
  203. /**
  204. * Decodes a BASE64 encoded byte array that is known to be reasonably well formatted. The method is about twice as
  205. * fast as {@link #decode(char[])}. The preconditions are:<br>
  206. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  207. * + Line separator must be "\r\n", as specified in RFC 2045
  208. * + The array must not contain illegal characters within the encoded string<br>
  209. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  210. *
  211. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  212. * @return The decoded UTF8 string. May be of length 0.
  213. */
  214. public static String decodeToStringFast(byte[] sArr) {
  215. return new String(decodeFast(sArr), UTF_8);
  216. }
  217. /**
  218. * Decodes a BASE64 encoded char array that is known to be reasonably well formatted. The method is about twice as
  219. * fast as {@link #decode(char[])}. The preconditions are:<br>
  220. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  221. * + Line separator must be "\r\n", as specified in RFC 2045
  222. * + The array must not contain illegal characters within the encoded string<br>
  223. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  224. *
  225. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  226. * @return The decoded UTF8 string. May be of length 0.
  227. */
  228. public static String decodeToStringFast(char[] sArr) {
  229. return new String(decodeFast(sArr), UTF_8);
  230. }
  231. /**
  232. * Decodes a BASE64 encoded char array that is known to be reasonably well formatted. The method is about twice as
  233. * fast as {@link #decode(char[])}. The preconditions are:<br>
  234. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  235. * + Line separator must be "\r\n", as specified in RFC 2045
  236. * + The array must not contain illegal characters within the encoded string<br>
  237. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  238. *
  239. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  240. * @return The decoded array of bytes. May be of length 0.
  241. */
  242. public static byte[] decodeFast(char[] sArr) {
  243. // Check special case
  244. int sLen = sArr.length;
  245. if (sLen == 0)
  246. return new byte[0];
  247. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  248. // Trim illegal chars from start
  249. while (sIx < eIx && IA[sArr[sIx]] < 0)
  250. sIx++;
  251. // Trim illegal chars from end
  252. while (eIx > 0 && IA[sArr[eIx]] < 0)
  253. eIx--;
  254. // get the padding count (=) (0, 1 or 2)
  255. int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
  256. int cCnt = eIx - sIx + 1; // Content count including possible separators
  257. int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
  258. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  259. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  260. // Decode all but the last 0 - 2 bytes.
  261. int d = 0;
  262. for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
  263. // Assemble three bytes into an int from four "valid" characters.
  264. int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
  265. // Add the bytes
  266. dArr[d++] = (byte) (i >> 16);
  267. dArr[d++] = (byte) (i >> 8);
  268. dArr[d++] = (byte) i;
  269. // If line separator, jump over it.
  270. if (sepCnt > 0 && ++cc == 19) {
  271. sIx += 2;
  272. cc = 0;
  273. }
  274. }
  275. if (d < len) {
  276. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  277. int i = 0;
  278. for (int j = 0; sIx <= eIx - pad; j++)
  279. i |= IA[sArr[sIx++]] << (18 - j * 6);
  280. for (int r = 16; d < len; r -= 8)
  281. dArr[d++] = (byte) (i >> r);
  282. }
  283. return dArr;
  284. }
  285. // ****************************************************************************************
  286. // * byte[] version
  287. // ****************************************************************************************
  288. /**
  289. * Encodes a raw byte array into a BASE64 <code>byte[]</code> representation in accordance with RFC 2045.
  290. *
  291. * @param string The string to convert. If <code>null</code> or length 0 an empty array will be returned.
  292. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  293. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  294. * little faster.
  295. * @return A BASE64 encoded array. Never <code>null</code>.
  296. */
  297. public static byte[] encodeToBytes(String string, boolean lineSep) {
  298. return encodeToBytes(string.getBytes(UTF_8), lineSep);
  299. }
  300. /**
  301. * Encodes a raw byte array into a BASE64 <code>byte[]</code> representation in accordance with RFC 2045.
  302. *
  303. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  304. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  305. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  306. * little faster.
  307. * @return A BASE64 encoded array. Never <code>null</code>.
  308. */
  309. public static byte[] encodeToBytes(byte[] sArr, boolean lineSep) {
  310. // Check special case
  311. int sLen = sArr != null ? sArr.length : 0;
  312. if (sLen == 0)
  313. return new byte[0];
  314. int eLen = (sLen / 3) * 3; // Length of even 24-bits.
  315. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
  316. int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
  317. byte[] dArr = new byte[dLen];
  318. // Encode even 24-bits
  319. for (int s = 0, d = 0, cc = 0; s < eLen; ) {
  320. // Copy next three bytes into lower 24 bits of int, paying attension to sign.
  321. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
  322. // Encode the int into four chars
  323. dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
  324. dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
  325. dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
  326. dArr[d++] = (byte) CA[i & 0x3f];
  327. // Add optional line separator
  328. if (lineSep && ++cc == 19 && d < dLen - 2) {
  329. dArr[d++] = '\r';
  330. dArr[d++] = '\n';
  331. cc = 0;
  332. }
  333. }
  334. // Pad and encode last bits if source isn't an even 24 bits.
  335. int left = sLen - eLen; // 0 - 2.
  336. if (left > 0) {
  337. // Prepare the int
  338. int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
  339. // Set last four chars
  340. dArr[dLen - 4] = (byte) CA[i >> 12];
  341. dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
  342. dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
  343. dArr[dLen - 1] = '=';
  344. }
  345. return dArr;
  346. }
  347. /**
  348. * Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle arrays both with
  349. * and without line separators.
  350. *
  351. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  352. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  353. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  354. */
  355. public static byte[] decode(byte[] sArr) {
  356. // Check special case
  357. int sLen = sArr.length;
  358. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  359. // so we don't have to reallocate & copy it later.
  360. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  361. for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
  362. if (IA[sArr[i] & 0xff] < 0)
  363. sepCnt++;
  364. // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
  365. if ((sLen - sepCnt) % 4 != 0)
  366. return null;
  367. int pad = 0;
  368. for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0; )
  369. if (sArr[i] == '=')
  370. pad++;
  371. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  372. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  373. for (int s = 0, d = 0; d < len; ) {
  374. // Assemble three bytes into an int from four "valid" characters.
  375. int i = 0;
  376. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  377. int c = IA[sArr[s++] & 0xff];
  378. if (c >= 0)
  379. i |= c << (18 - j * 6);
  380. else
  381. j--;
  382. }
  383. // Add the bytes
  384. dArr[d++] = (byte) (i >> 16);
  385. if (d < len) {
  386. dArr[d++] = (byte) (i >> 8);
  387. if (d < len)
  388. dArr[d++] = (byte) i;
  389. }
  390. }
  391. return dArr;
  392. }
  393. /**
  394. * Decodes a BASE64 encoded byte array that is known to be reasonably well formatted. The method is about twice as
  395. * fast as {@link #decode(byte[])}. The preconditions are:<br>
  396. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  397. * + Line separator must be "\r\n", as specified in RFC 2045
  398. * + The array must not contain illegal characters within the encoded string<br>
  399. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  400. *
  401. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
  402. * @return The decoded array of bytes. May be of length 0.
  403. */
  404. public static byte[] decodeFast(byte[] sArr) {
  405. // Check special case
  406. int sLen = sArr.length;
  407. if (sLen == 0)
  408. return new byte[0];
  409. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  410. // Trim illegal chars from start
  411. while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
  412. sIx++;
  413. // Trim illegal chars from end
  414. while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
  415. eIx--;
  416. // get the padding count (=) (0, 1 or 2)
  417. int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
  418. int cCnt = eIx - sIx + 1; // Content count including possible separators
  419. int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
  420. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  421. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  422. // Decode all but the last 0 - 2 bytes.
  423. int d = 0;
  424. for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
  425. // Assemble three bytes into an int from four "valid" characters.
  426. int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
  427. // Add the bytes
  428. dArr[d++] = (byte) (i >> 16);
  429. dArr[d++] = (byte) (i >> 8);
  430. dArr[d++] = (byte) i;
  431. // If line separator, jump over it.
  432. if (sepCnt > 0 && ++cc == 19) {
  433. sIx += 2;
  434. cc = 0;
  435. }
  436. }
  437. if (d < len) {
  438. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  439. int i = 0;
  440. for (int j = 0; sIx <= eIx - pad; j++)
  441. i |= IA[sArr[sIx++]] << (18 - j * 6);
  442. for (int r = 16; d < len; r -= 8)
  443. dArr[d++] = (byte) (i >> r);
  444. }
  445. return dArr;
  446. }
  447. // ****************************************************************************************
  448. // * String version
  449. // ****************************************************************************************
  450. /**
  451. * Encodes a UTF-8 string into a BASE64 <code>String</code> representation in accordance with RFC 2045.
  452. *
  453. * @param string The string to convert. If <code>null</code> or length 0 an empty array will be returned.
  454. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  455. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  456. * little faster.
  457. * @return A BASE64 encoded array. Never <code>null</code>.
  458. */
  459. public static String encodeToString(String string, boolean lineSep) {
  460. return encodeToString(string.getBytes(UTF_8), lineSep);
  461. }
  462. /**
  463. * Encodes a raw byte array into a BASE64 <code>String</code> representation in accordance with RFC 2045.
  464. *
  465. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  466. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  467. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  468. * little faster.
  469. * @return A BASE64 encoded array. Never <code>null</code>.
  470. */
  471. public static String encodeToString(byte[] sArr, boolean lineSep) {
  472. // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
  473. return new String(encodeToChars(sArr, lineSep));
  474. }
  475. /**
  476. * Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle
  477. * strings both with and without line separators.<br>
  478. * <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
  479. * will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
  480. *
  481. * @param string The source string. <code>null</code> or length 0 will return an empty array.
  482. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  483. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  484. */
  485. public static String decodeToString(String string) {
  486. return new String(decode(string), UTF_8);
  487. }
  488. /**
  489. * Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle
  490. * strings both with and without line separators.<br>
  491. * <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
  492. * will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
  493. *
  494. * @param string The source string. <code>null</code> or length 0 will return an empty array.
  495. * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
  496. * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
  497. */
  498. public static byte[] decode(String string) {
  499. // Check special case
  500. int sLen = string != null ? string.length() : 0;
  501. if (sLen == 0)
  502. return new byte[0];
  503. // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
  504. // so we don't have to reallocate & copy it later.
  505. int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
  506. for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
  507. if (IA[string.charAt(i)] < 0)
  508. sepCnt++;
  509. // Check so that legal chars (including '=') are evenly dividable by 4 as specified in RFC 2045.
  510. if ((sLen - sepCnt) % 4 != 0)
  511. return null;
  512. // Count '=' at end
  513. int pad = 0;
  514. for (int i = sLen; i > 1 && IA[string.charAt(--i)] <= 0; )
  515. if (string.charAt(i) == '=')
  516. pad++;
  517. int len = ((sLen - sepCnt) * 6 >> 3) - pad;
  518. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  519. for (int s = 0, d = 0; d < len; ) {
  520. // Assemble three bytes into an int from four "valid" characters.
  521. int i = 0;
  522. for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
  523. int c = IA[string.charAt(s++)];
  524. if (c >= 0)
  525. i |= c << (18 - j * 6);
  526. else
  527. j--;
  528. }
  529. // Add the bytes
  530. dArr[d++] = (byte) (i >> 16);
  531. if (d < len) {
  532. dArr[d++] = (byte) (i >> 8);
  533. if (d < len)
  534. dArr[d++] = (byte) i;
  535. }
  536. }
  537. return dArr;
  538. }
  539. /**
  540. * Decodes a BASE64 encoded string that is known to be reasonably well formatted. The method is about twice as
  541. * fast as {@link #decode(String)}. The preconditions are:<br>
  542. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  543. * + Line separator must be "\r\n", as specified in RFC 2045
  544. * + The array must not contain illegal characters within the encoded string<br>
  545. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  546. *
  547. * @param string The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
  548. * @return The decoded UTF8 string. May be of length 0.
  549. */
  550. public static String decodeToStringFast(String string) {
  551. return new String(decodeFast(string), UTF_8);
  552. }
  553. /**
  554. * Decodes a BASE64 encoded string that is known to be reasonably well formatted. The method is about twice as
  555. * fast as {@link #decode(String)}. The preconditions are:<br>
  556. * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
  557. * + Line separator must be "\r\n", as specified in RFC 2045
  558. * + The array must not contain illegal characters within the encoded string<br>
  559. * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
  560. *
  561. * @param string The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
  562. * @return The decoded array of bytes. May be of length 0.
  563. */
  564. public static byte[] decodeFast(String string) {
  565. // Check special case
  566. int sLen = string.length();
  567. if (sLen == 0)
  568. return new byte[0];
  569. int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
  570. // Trim illegal chars from start
  571. while (sIx < eIx && IA[string.charAt(sIx) & 0xff] < 0)
  572. sIx++;
  573. // Trim illegal chars from end
  574. while (eIx > 0 && IA[string.charAt(eIx) & 0xff] < 0)
  575. eIx--;
  576. // get the padding count (=) (0, 1 or 2)
  577. int pad = string.charAt(eIx) == '=' ? (string.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
  578. int cCnt = eIx - sIx + 1; // Content count including possible separators
  579. int sepCnt = sLen > 76 ? (string.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
  580. int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
  581. byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
  582. // Decode all but the last 0 - 2 bytes.
  583. int d = 0;
  584. for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
  585. // Assemble three bytes into an int from four "valid" characters.
  586. int i = IA[string.charAt(sIx++)] << 18 | IA[string.charAt(sIx++)] << 12 | IA[string.charAt(sIx++)] << 6 | IA[string.charAt(sIx++)];
  587. // Add the bytes
  588. dArr[d++] = (byte) (i >> 16);
  589. dArr[d++] = (byte) (i >> 8);
  590. dArr[d++] = (byte) i;
  591. // If line separator, jump over it.
  592. if (sepCnt > 0 && ++cc == 19) {
  593. sIx += 2;
  594. cc = 0;
  595. }
  596. }
  597. if (d < len) {
  598. // Decode last 1-3 bytes (incl '=') into 1-3 bytes
  599. int i = 0;
  600. for (int j = 0; sIx <= eIx - pad; j++)
  601. i |= IA[string.charAt(sIx++)] << (18 - j * 6);
  602. for (int r = 16; d < len; r -= 8)
  603. dArr[d++] = (byte) (i >> r);
  604. }
  605. return dArr;
  606. }
  607. private Base64() {
  608. // disabled
  609. }
  610. }