PageRenderTime 58ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/utils/src/main/java/com/sun/grizzly/util/buf/Base64Utils.java

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