PageRenderTime 41ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/Commons/src/com/aionemu/commons/utils/Base64.java

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