001/** 002 * GRANITE DATA SERVICES 003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S. 004 * 005 * This file is part of the Granite Data Services Platform. 006 * 007 * Granite Data Services is free software; you can redistribute it and/or 008 * modify it under the terms of the GNU Lesser General Public 009 * License as published by the Free Software Foundation; either 010 * version 2.1 of the License, or (at your option) any later version. 011 * 012 * Granite Data Services is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 015 * General Public License for more details. 016 * 017 * You should have received a copy of the GNU Lesser General Public 018 * License along with this library; if not, write to the Free Software 019 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 020 * USA, or see <http://www.gnu.org/licenses/>. 021 */ 022package org.granite.util; 023 024import java.util.Arrays; 025 026/** A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance 027 * with RFC 2045.<br><br> 028 * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster 029 * on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes) 030 * compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br> 031 * 032 * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and 033 * about 50% faster for decoding large arrays. This implementation is about twice as fast on very small 034 * arrays (< 30 bytes). If source/destination is a <code>String</code> this 035 * version is about three times as fast due to the fact that the Commons Codec result has to be recoded 036 * to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br> 037 * 038 * This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only 039 * allocates the resulting array. This produces less garbage and it is possible to handle arrays twice 040 * as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown 041 * whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance 042 * is quite low it probably does.<br><br> 043 * 044 * The encoder produces the same output as the Sun one except that the Sun's encoder appends 045 * a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the 046 * length and is probably a side effect. Both are in conformance with RFC 2045 though.<br> 047 * Commons codec seem to always att a trailing line separator.<br><br> 048 * 049 * <b>Note!</b> 050 * The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and 051 * thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different 052 * format types. The methods not used can simply be commented out.<br><br> 053 * 054 * There is also a "fast" version of all decode methods that works the same way as the normal ones, but 055 * har a few demands on the decoded input. Normally though, these fast verions should be used if the source if 056 * the input is known and it hasn't bee tampered with.<br><br> 057 * 058 * If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com. 059 * 060 * Licence (BSD): 061 * ============== 062 * 063 * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com) 064 * All rights reserved. 065 * 066 * Redistribution and use in source and binary forms, with or without modification, 067 * are permitted provided that the following conditions are met: 068 * Redistributions of source code must retain the above copyright notice, this list 069 * of conditions and the following disclaimer. 070 * Redistributions in binary form must reproduce the above copyright notice, this 071 * list of conditions and the following disclaimer in the documentation and/or other 072 * materials provided with the distribution. 073 * Neither the name of the MiG InfoCom AB nor the names of its contributors may be 074 * used to endorse or promote products derived from this software without specific 075 * prior written permission. 076 * 077 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 078 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 079 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 080 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 081 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 082 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 083 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 084 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 085 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 086 * OF SUCH DAMAGE. 087 * 088 * @version 2.2 089 * @author Mikael Grev 090 * Date: 2004-aug-02 091 * Time: 11:31:11 092 */ 093 094public class Base64 095{ 096 private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); 097 private static final int[] IA = new int[256]; 098 static { 099 Arrays.fill(IA, -1); 100 for (int i = 0, iS = CA.length; i < iS; i++) 101 IA[CA[i]] = i; 102 IA['='] = 0; 103 } 104 105 // **************************************************************************************** 106 // * char[] version 107 // **************************************************************************************** 108 109 /** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045. 110 * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned. 111 * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br> 112 * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a 113 * little faster. 114 * @return A BASE64 encoded array. Never <code>null</code>. 115 */ 116 public final static char[] encodeToChar(byte[] sArr, boolean lineSep) 117 { 118 // Check special case 119 if (sArr == null || sArr.length == 0) 120 return new char[0]; 121 122 int sLen = sArr.length; 123 int eLen = (sLen / 3) * 3; // Length of even 24-bits. 124 int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count 125 int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array 126 char[] dArr = new char[dLen]; 127 128 // Encode even 24-bits 129 for (int s = 0, d = 0, cc = 0; s < eLen;) { 130 // Copy next three bytes into lower 24 bits of int, paying attension to sign. 131 int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); 132 133 // Encode the int into four chars 134 dArr[d++] = CA[(i >>> 18) & 0x3f]; 135 dArr[d++] = CA[(i >>> 12) & 0x3f]; 136 dArr[d++] = CA[(i >>> 6) & 0x3f]; 137 dArr[d++] = CA[i & 0x3f]; 138 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 147 // Pad and encode last bits if source isn't even 24 bits. 148 int left = sLen - eLen; // 0 - 2. 149 if (left > 0) { 150 // Prepare the int 151 int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); 152 153 // Set last four chars 154 dArr[dLen - 4] = CA[i >> 12]; 155 dArr[dLen - 3] = CA[(i >>> 6) & 0x3f]; 156 dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '='; 157 dArr[dLen - 1] = '='; 158 } 159 return dArr; 160 } 161 162 /** Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with 163 * and without line separators. 164 * @param sArr The source array. <code>null</code> or length 0 will return an empty array. 165 * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters 166 * (including '=') isn't divideable by 4. (I.e. definitely corrupted). 167 */ 168 public final static byte[] decode(char[] sArr) 169 { 170 // Check special case 171 if (sArr == null || sArr.length == 0) 172 return new byte[0]; 173 174 int sLen = sArr.length; 175 176 // Count illegal characters (including '\r', '\n') to know what size the returned array will be, 177 // so we don't have to reallocate & copy it later. 178 int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...) 179 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. 180 if (IA[sArr[i]] < 0) 181 sepCnt++; 182 183 // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045. 184 if ((sLen - sepCnt) % 4 != 0) 185 return null; 186 187 int pad = 0; 188 for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0;) 189 if (sArr[i] == '=') 190 pad++; 191 192 int len = ((sLen - sepCnt) * 6 >> 3) - pad; 193 194 byte[] dArr = new byte[len]; // Preallocate byte[] of exact length 195 196 for (int s = 0, d = 0; d < len;) { 197 // Assemble three bytes into an int from four "valid" characters. 198 int i = 0; 199 for (int j = 0; j < 4; j++) { // j only increased if a valid char was found. 200 int c = IA[sArr[s++]]; 201 if (c >= 0) 202 i |= c << (18 - j * 6); 203 else 204 j--; 205 } 206 // Add the bytes 207 dArr[d++] = (byte) (i >> 16); 208 if (d < len) { 209 dArr[d++]= (byte) (i >> 8); 210 if (d < len) 211 dArr[d++] = (byte) i; 212 } 213 } 214 return dArr; 215 } 216 217 /** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as 218 * fast as {@link #decode(char[])}. The preconditions are:<br> 219 * + The array must have a line length of 76 chars OR no line separators at all (one line).<br> 220 * + Line separator must be "\r\n", as specified in RFC 2045 221 * + The array must not contain illegal characters within the encoded string<br> 222 * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> 223 * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception. 224 * @return The decoded array of bytes. May be of length 0. 225 */ 226 public final static byte[] decodeFast(char[] sArr) 227 { 228 // Check special case 229 int sLen = sArr.length; 230 if (sLen == 0) 231 return new byte[0]; 232 233 int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. 234 235 // Trim illegal chars from start 236 while (sIx < eIx && IA[sArr[sIx]] < 0) 237 sIx++; 238 239 // Trim illegal chars from end 240 while (eIx > 0 && IA[sArr[eIx]] < 0) 241 eIx--; 242 243 // get the padding count (=) (0, 1 or 2) 244 int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end. 245 int cCnt = eIx - sIx + 1; // Content count including possible separators 246 int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; 247 248 int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes 249 byte[] dArr = new byte[len]; // Preallocate byte[] of exact length 250 251 // Decode all but the last 0 - 2 bytes. 252 int d = 0; 253 for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { 254 // Assemble three bytes into an int from four "valid" characters. 255 int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; 256 257 // Add the bytes 258 dArr[d++] = (byte) (i >> 16); 259 dArr[d++] = (byte) (i >> 8); 260 dArr[d++] = (byte) i; 261 262 // If line separator, jump over it. 263 if (sepCnt > 0 && ++cc == 19) { 264 sIx += 2; 265 cc = 0; 266 } 267 } 268 269 if (d < len) { 270 // Decode last 1-3 bytes (incl '=') into 1-3 bytes 271 int i = 0; 272 for (int j = 0; sIx <= eIx - pad; j++) 273 i |= IA[sArr[sIx++]] << (18 - j * 6); 274 275 for (int r = 16; d < len; r -= 8) 276 dArr[d++] = (byte) (i >> r); 277 } 278 279 return dArr; 280 } 281 282 // **************************************************************************************** 283 // * byte[] version 284 // **************************************************************************************** 285 286 /** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045. 287 * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned. 288 * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br> 289 * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a 290 * little faster. 291 * @return A BASE64 encoded array. Never <code>null</code>. 292 */ 293 public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) 294 { 295 // Check special case 296 if (sArr == null || sArr.length == 0) 297 return new byte[0]; 298 299 int sLen = sArr.length; 300 int eLen = (sLen / 3) * 3; // Length of even 24-bits. 301 int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count 302 int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array 303 byte[] dArr = new byte[dLen]; 304 305 // Encode even 24-bits 306 for (int s = 0, d = 0, cc = 0; s < eLen;) { 307 // Copy next three bytes into lower 24 bits of int, paying attension to sign. 308 int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); 309 310 // Encode the int into four chars 311 dArr[d++] = (byte) CA[(i >>> 18) & 0x3f]; 312 dArr[d++] = (byte) CA[(i >>> 12) & 0x3f]; 313 dArr[d++] = (byte) CA[(i >>> 6) & 0x3f]; 314 dArr[d++] = (byte) CA[i & 0x3f]; 315 316 // Add optional line separator 317 if (lineSep && ++cc == 19 && d < dLen - 2) { 318 dArr[d++] = '\r'; 319 dArr[d++] = '\n'; 320 cc = 0; 321 } 322 } 323 324 // Pad and encode last bits if source isn't an even 24 bits. 325 int left = sLen - eLen; // 0 - 2. 326 if (left > 0) { 327 // Prepare the int 328 int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); 329 330 // Set last four chars 331 dArr[dLen - 4] = (byte) CA[i >> 12]; 332 dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f]; 333 dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '='; 334 dArr[dLen - 1] = '='; 335 } 336 return dArr; 337 } 338 339 /** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with 340 * and without line separators. 341 * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception. 342 * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters 343 * (including '=') isn't divideable by 4. (I.e. definitely corrupted). 344 */ 345 public final static byte[] decode(byte[] sArr) 346 { 347 // Check special case 348 int sLen = sArr.length; 349 350 // Count illegal characters (including '\r', '\n') to know what size the returned array will be, 351 // so we don't have to reallocate & copy it later. 352 int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...) 353 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. 354 if (IA[sArr[i] & 0xff] < 0) 355 sepCnt++; 356 357 // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045. 358 if ((sLen - sepCnt) % 4 != 0) 359 return null; 360 361 int pad = 0; 362 for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;) 363 if (sArr[i] == '=') 364 pad++; 365 366 int len = ((sLen - sepCnt) * 6 >> 3) - pad; 367 368 byte[] dArr = new byte[len]; // Preallocate byte[] of exact length 369 370 for (int s = 0, d = 0; d < len;) { 371 // Assemble three bytes into an int from four "valid" characters. 372 int i = 0; 373 for (int j = 0; j < 4; j++) { // j only increased if a valid char was found. 374 int c = IA[sArr[s++] & 0xff]; 375 if (c >= 0) 376 i |= c << (18 - j * 6); 377 else 378 j--; 379 } 380 381 // Add the bytes 382 dArr[d++] = (byte) (i >> 16); 383 if (d < len) { 384 dArr[d++]= (byte) (i >> 8); 385 if (d < len) 386 dArr[d++] = (byte) i; 387 } 388 } 389 390 return dArr; 391 } 392 393 394 /** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as 395 * fast as {@link #decode(byte[])}. The preconditions are:<br> 396 * + The array must have a line length of 76 chars OR no line separators at all (one line).<br> 397 * + Line separator must be "\r\n", as specified in RFC 2045 398 * + The array must not contain illegal characters within the encoded string<br> 399 * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> 400 * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception. 401 * @return The decoded array of bytes. May be of length 0. 402 */ 403 public final static byte[] decodeFast(byte[] sArr) 404 { 405 // Check special case 406 int sLen = sArr.length; 407 if (sLen == 0) 408 return new byte[0]; 409 410 int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. 411 412 // Trim illegal chars from start 413 while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0) 414 sIx++; 415 416 // Trim illegal chars from end 417 while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0) 418 eIx--; 419 420 // get the padding count (=) (0, 1 or 2) 421 int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end. 422 int cCnt = eIx - sIx + 1; // Content count including possible separators 423 int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; 424 425 int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes 426 byte[] dArr = new byte[len]; // Preallocate byte[] of exact length 427 428 // Decode all but the last 0 - 2 bytes. 429 int d = 0; 430 for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { 431 // Assemble three bytes into an int from four "valid" characters. 432 int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; 433 434 // Add the bytes 435 dArr[d++] = (byte) (i >> 16); 436 dArr[d++] = (byte) (i >> 8); 437 dArr[d++] = (byte) i; 438 439 // If line separator, jump over it. 440 if (sepCnt > 0 && ++cc == 19) { 441 sIx += 2; 442 cc = 0; 443 } 444 } 445 446 if (d < len) { 447 // Decode last 1-3 bytes (incl '=') into 1-3 bytes 448 int i = 0; 449 for (int j = 0; sIx <= eIx - pad; j++) 450 i |= IA[sArr[sIx++]] << (18 - j * 6); 451 452 for (int r = 16; d < len; r -= 8) 453 dArr[d++] = (byte) (i >> r); 454 } 455 456 return dArr; 457 } 458 459 // **************************************************************************************** 460 // * String version 461 // **************************************************************************************** 462 463 /** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045. 464 * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned. 465 * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br> 466 * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a 467 * little faster. 468 * @return A BASE64 encoded array. Never <code>null</code>. 469 */ 470 public final static String encodeToString(byte[] sArr, boolean lineSep) 471 { 472 // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower. 473 return new String(encodeToChar(sArr, lineSep)); 474 } 475 476 /** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with 477 * and without line separators.<br> 478 * <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That 479 * will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string. 480 * @param str The source string. <code>null</code> or length 0 will return an empty array. 481 * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters 482 * (including '=') isn't divideable by 4. (I.e. definitely corrupted). 483 */ 484 public final static byte[] decode(String str) 485 { 486 // Check special case 487 if (str == null || str.length() == 0) 488 return new byte[0]; 489 490 int sLen = str.length(); 491 492 // Count illegal characters (including '\r', '\n') to know what size the returned array will be, 493 // so we don't have to reallocate & copy it later. 494 int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...) 495 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. 496 if (IA[str.charAt(i)] < 0) 497 sepCnt++; 498 499 // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045. 500 if ((sLen - sepCnt) % 4 != 0) 501 return null; 502 503 // Count '=' at end 504 int pad = 0; 505 for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;) 506 if (str.charAt(i) == '=') 507 pad++; 508 509 int len = ((sLen - sepCnt) * 6 >> 3) - pad; 510 511 byte[] dArr = new byte[len]; // Preallocate byte[] of exact length 512 513 for (int s = 0, d = 0; d < len;) { 514 // Assemble three bytes into an int from four "valid" characters. 515 int i = 0; 516 for (int j = 0; j < 4; j++) { // j only increased if a valid char was found. 517 int c = IA[str.charAt(s++)]; 518 if (c >= 0) 519 i |= c << (18 - j * 6); 520 else 521 j--; 522 } 523 // Add the bytes 524 dArr[d++] = (byte) (i >> 16); 525 if (d < len) { 526 dArr[d++]= (byte) (i >> 8); 527 if (d < len) 528 dArr[d++] = (byte) i; 529 } 530 } 531 return dArr; 532 } 533 534 /** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as 535 * fast as {@link #decode(String)}. The preconditions are:<br> 536 * + The array must have a line length of 76 chars OR no line separators at all (one line).<br> 537 * + Line separator must be "\r\n", as specified in RFC 2045 538 * + The array must not contain illegal characters within the encoded string<br> 539 * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> 540 * @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception. 541 * @return The decoded array of bytes. May be of length 0. 542 */ 543 public final static byte[] decodeFast(String s) 544 { 545 // Check special case 546 if (s == null || s.length() == 0) 547 return new byte[0]; 548 549 int sLen = s.length(); 550 int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. 551 552 // Trim illegal chars from start 553 while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) 554 sIx++; 555 556 // Trim illegal chars from end 557 while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) 558 eIx--; 559 560 // get the padding count (=) (0, 1 or 2) 561 int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. 562 int cCnt = eIx - sIx + 1; // Content count including possible separators 563 int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; 564 565 int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes 566 byte[] dArr = new byte[len]; // Preallocate byte[] of exact length 567 568 // Decode all but the last 0 - 2 bytes. 569 int d = 0; 570 for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { 571 // Assemble three bytes into an int from four "valid" characters. 572 int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)]; 573 574 // Add the bytes 575 dArr[d++] = (byte) (i >> 16); 576 dArr[d++] = (byte) (i >> 8); 577 dArr[d++] = (byte) i; 578 579 // If line separator, jump over it. 580 if (sepCnt > 0 && ++cc == 19) { 581 sIx += 2; 582 cc = 0; 583 } 584 } 585 586 if (d < len) { 587 // Decode last 1-3 bytes (incl '=') into 1-3 bytes 588 int i = 0; 589 for (int j = 0; sIx <= eIx - pad; j++) 590 i |= IA[s.charAt(sIx++)] << (18 - j * 6); 591 592 for (int r = 16; d < len; r -= 8) 593 dArr[d++] = (byte) (i >> r); 594 } 595 596 return dArr; 597 } 598}