PageRenderTime 60ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/commons/src/commons/utils/Base64.java

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