Java IRC bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Base64.java 28KB

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