PageRenderTime 67ms CodeModel.GetById 5ms RepoModel.GetById 0ms app.codeStats 0ms

/parboiled-core/src/main/java/org/parboiled/common/Base64.java

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