1 /* 2 * reserved comment block 3 * DO NOT REMOVE OR ALTER! 4 */ 5 /* 6 * Copyright 1999-2004 The Apache Software Foundation. 7 * 8 * Licensed under the Apache License, Version 2.0 (the "License"); 9 * you may not use this file except in compliance with the License. 10 * You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, software 15 * distributed under the License is distributed on an "AS IS" BASIS, 16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 * See the License for the specific language governing permissions and 18 * limitations under the License. 19 * 20 */ 21 package com.sun.org.apache.xml.internal.security.utils; 22 23 import java.io.BufferedReader; 24 import java.io.IOException; 25 import java.io.InputStream; 26 import java.io.OutputStream; 27 import java.math.BigInteger; 28 29 import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; 30 import org.w3c.dom.Document; 31 import org.w3c.dom.Element; 32 import org.w3c.dom.Node; 33 import org.w3c.dom.Text; 34 35 36 /** 37 * Implementation of MIME's Base64 encoding and decoding conversions. 38 * Optimized code. (raw version taken from oreilly.jonathan.util, 39 * and currently com.sun.org.apache.xerces.internal.ds.util.Base64) 40 * 41 * @author Raul Benito(Of the xerces copy, and little adaptations). 42 * @author Anli Shundi 43 * @author Christian Geuer-Pollmann 44 * @see <A HREF="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</A> 45 * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode 46 */ 47 public class Base64 { 48 49 50 /** Field BASE64DEFAULTLENGTH */ 51 public static final int BASE64DEFAULTLENGTH = 76; 52 53 private Base64() { 54 // we don't allow instantiation 55 } 56 57 /** 58 * Returns a byte-array representation of a <code>{@link BigInteger}<code>. 59 * No sign-bit is outputed. 60 * 61 * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray 62 * retunrs eventually longer arrays because of the leading sign-bit. 63 * 64 * @param big <code>BigInteger<code> to be converted 65 * @param bitlen <code>int<code> the desired length in bits of the representation 66 * @return a byte array with <code>bitlen</code> bits of <code>big</code> 67 */ 68 static final byte[] getBytes(BigInteger big, int bitlen) { 69 70 //round bitlen 71 bitlen = ((bitlen + 7) >> 3) << 3; 72 73 if (bitlen < big.bitLength()) { 74 throw new IllegalArgumentException(I18n 75 .translate("utils.Base64.IllegalBitlength")); 76 } 77 78 byte[] bigBytes = big.toByteArray(); 79 80 if (((big.bitLength() % 8) != 0) 81 && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { 82 return bigBytes; 83 } 84 85 // some copying needed 86 int startSrc = 0; // no need to skip anything 87 int bigLen = bigBytes.length; //valid length of the string 88 89 if ((big.bitLength() % 8) == 0) { // correct values 90 startSrc = 1; // skip sign bit 91 92 bigLen--; // valid length of the string 93 } 94 95 int startDst = bitlen / 8 - bigLen; //pad with leading nulls 96 byte[] resizedBytes = new byte[bitlen / 8]; 97 98 System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); 99 100 return resizedBytes; 101 102 } 103 104 /** 105 * Encode in Base64 the given <code>{@link BigInteger}<code>. 106 * 107 * @param big 108 * @return String with Base64 encoding 109 */ 110 public static final String encode(BigInteger big) { 111 return encode(getBytes(big, big.bitLength())); 112 } 113 114 /** 115 * Returns a byte-array representation of a <code>{@link BigInteger}<code>. 116 * No sign-bit is outputed. 117 * 118 * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray 119 * retunrs eventually longer arrays because of the leading sign-bit. 120 * 121 * @param big <code>BigInteger<code> to be converted 122 * @param bitlen <code>int<code> the desired length in bits of the representation 123 * @return a byte array with <code>bitlen</code> bits of <code>big</code> 124 */ 125 public static final byte[] encode(BigInteger big, int bitlen) { 126 127 //round bitlen 128 bitlen = ((bitlen + 7) >> 3) << 3; 129 130 if (bitlen < big.bitLength()) { 131 throw new IllegalArgumentException(I18n 132 .translate("utils.Base64.IllegalBitlength")); 133 } 134 135 byte[] bigBytes = big.toByteArray(); 136 137 if (((big.bitLength() % 8) != 0) 138 && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { 139 return bigBytes; 140 } 141 142 // some copying needed 143 int startSrc = 0; // no need to skip anything 144 int bigLen = bigBytes.length; //valid length of the string 145 146 if ((big.bitLength() % 8) == 0) { // correct values 147 startSrc = 1; // skip sign bit 148 149 bigLen--; // valid length of the string 150 } 151 152 int startDst = bitlen / 8 - bigLen; //pad with leading nulls 153 byte[] resizedBytes = new byte[bitlen / 8]; 154 155 System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); 156 157 return resizedBytes; 158 159 } 160 161 /** 162 * Method decodeBigIntegerFromElement 163 * 164 * @param element 165 * @return the biginter obtained from the node 166 * @throws Base64DecodingException 167 */ 168 public static final BigInteger decodeBigIntegerFromElement(Element element) throws Base64DecodingException 169 { 170 return new BigInteger(1, Base64.decode(element)); 171 } 172 173 /** 174 * Method decodeBigIntegerFromText 175 * 176 * @param text 177 * @return the biginter obtained from the text node 178 * @throws Base64DecodingException 179 */ 180 public static final BigInteger decodeBigIntegerFromText(Text text) throws Base64DecodingException 181 { 182 return new BigInteger(1, Base64.decode(text.getData())); 183 } 184 185 /** 186 * This method takes an (empty) Element and a BigInteger and adds the 187 * base64 encoded BigInteger to the Element. 188 * 189 * @param element 190 * @param biginteger 191 */ 192 public static final void fillElementWithBigInteger(Element element, 193 BigInteger biginteger) { 194 195 String encodedInt = encode(biginteger); 196 197 if (encodedInt.length() > 76) { 198 encodedInt = "\n" + encodedInt + "\n"; 199 } 200 201 Document doc = element.getOwnerDocument(); 202 Text text = doc.createTextNode(encodedInt); 203 204 element.appendChild(text); 205 } 206 207 /** 208 * Method decode 209 * 210 * Takes the <CODE>Text</CODE> children of the Element and interprets 211 * them as input for the <CODE>Base64.decode()</CODE> function. 212 * 213 * @param element 214 * @return the byte obtained of the decoding the element 215 * $todo$ not tested yet 216 * @throws Base64DecodingException 217 */ 218 public static final byte[] decode(Element element) throws Base64DecodingException { 219 220 Node sibling = element.getFirstChild(); 221 StringBuffer sb = new StringBuffer(); 222 223 while (sibling!=null) { 224 if (sibling.getNodeType() == Node.TEXT_NODE) { 225 Text t = (Text) sibling; 226 227 sb.append(t.getData()); 228 } 229 sibling=sibling.getNextSibling(); 230 } 231 232 return decode(sb.toString()); 233 } 234 235 /** 236 * Method encodeToElement 237 * 238 * @param doc 239 * @param localName 240 * @param bytes 241 * @return an Element with the base64 encoded in the text. 242 * 243 */ 244 public static final Element encodeToElement(Document doc, String localName, 245 byte[] bytes) { 246 247 Element el = XMLUtils.createElementInSignatureSpace(doc, localName); 248 Text text = doc.createTextNode(encode(bytes)); 249 250 el.appendChild(text); 251 252 return el; 253 } 254 255 /** 256 * Method decode 257 * 258 * 259 * @param base64 260 * @return the UTF bytes of the base64 261 * @throws Base64DecodingException 262 * 263 */ 264 public final static byte[] decode(byte[] base64) throws Base64DecodingException { 265 return decodeInternal(base64, -1); 266 } 267 268 269 270 /** 271 * Encode a byte array and fold lines at the standard 76th character unless 272 * ignore line breaks property is set. 273 * 274 * @param binaryData <code>byte[]<code> to be base64 encoded 275 * @return the <code>String<code> with encoded data 276 */ 277 public static final String encode(byte[] binaryData) { 278 return XMLUtils.ignoreLineBreaks() 279 ? encode(binaryData, Integer.MAX_VALUE) 280 : encode(binaryData, BASE64DEFAULTLENGTH); 281 } 282 283 /** 284 * Base64 decode the lines from the reader and return an InputStream 285 * with the bytes. 286 * 287 * 288 * @param reader 289 * @return InputStream with the decoded bytes 290 * @exception IOException passes what the reader throws 291 * @throws IOException 292 * @throws Base64DecodingException 293 */ 294 public final static byte[] decode(BufferedReader reader) 295 throws IOException, Base64DecodingException { 296 297 UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); 298 String line; 299 300 while (null != (line = reader.readLine())) { 301 byte[] bytes = decode(line); 302 303 baos.write(bytes); 304 } 305 306 return baos.toByteArray(); 307 } 308 309 static private final int BASELENGTH = 255; 310 static private final int LOOKUPLENGTH = 64; 311 static private final int TWENTYFOURBITGROUP = 24; 312 static private final int EIGHTBIT = 8; 313 static private final int SIXTEENBIT = 16; 314 static private final int FOURBYTE = 4; 315 static private final int SIGN = -128; 316 static private final char PAD = '='; 317 static final private byte [] base64Alphabet = new byte[BASELENGTH]; 318 static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; 319 320 static { 321 322 for (int i = 0; i<BASELENGTH; i++) { 323 base64Alphabet[i] = -1; 324 } 325 for (int i = 'Z'; i >= 'A'; i--) { 326 base64Alphabet[i] = (byte) (i-'A'); 327 } 328 for (int i = 'z'; i>= 'a'; i--) { 329 base64Alphabet[i] = (byte) ( i-'a' + 26); 330 } 331 332 for (int i = '9'; i >= '0'; i--) { 333 base64Alphabet[i] = (byte) (i-'0' + 52); 334 } 335 336 base64Alphabet['+'] = 62; 337 base64Alphabet['/'] = 63; 338 339 for (int i = 0; i<=25; i++) 340 lookUpBase64Alphabet[i] = (char)('A'+i); 341 342 for (int i = 26, j = 0; i<=51; i++, j++) 343 lookUpBase64Alphabet[i] = (char)('a'+ j); 344 345 for (int i = 52, j = 0; i<=61; i++, j++) 346 lookUpBase64Alphabet[i] = (char)('0' + j); 347 lookUpBase64Alphabet[62] = '+'; 348 lookUpBase64Alphabet[63] = '/'; 349 350 } 351 352 protected static final boolean isWhiteSpace(byte octect) { 353 return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); 354 } 355 356 protected static final boolean isPad(byte octect) { 357 return (octect == PAD); 358 } 359 360 361 /** 362 * Encodes hex octects into Base64 363 * 364 * @param binaryData Array containing binaryData 365 * @return Encoded Base64 array 366 */ 367 /** 368 * Encode a byte array in Base64 format and return an optionally 369 * wrapped line. 370 * 371 * @param binaryData <code>byte[]</code> data to be encoded 372 * @param length <code>int<code> length of wrapped lines; No wrapping if less than 4. 373 * @return a <code>String</code> with encoded data 374 */ 375 public static final String encode(byte[] binaryData,int length) { 376 377 if (length<4) { 378 length=Integer.MAX_VALUE; 379 } 380 381 if (binaryData == null) 382 return null; 383 384 int lengthDataBits = binaryData.length*EIGHTBIT; 385 if (lengthDataBits == 0) { 386 return ""; 387 } 388 389 int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; 390 int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; 391 int numberQuartet = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets; 392 int quartesPerLine = length/4; 393 int numberLines = (numberQuartet-1)/quartesPerLine; 394 char encodedData[] = null; 395 396 encodedData = new char[numberQuartet*4+numberLines]; 397 398 byte k=0, l=0, b1=0,b2=0,b3=0; 399 400 int encodedIndex = 0; 401 int dataIndex = 0; 402 int i = 0; 403 404 405 for (int line = 0; line < numberLines; line++) { 406 for (int quartet = 0; quartet < 19; quartet++) { 407 b1 = binaryData[dataIndex++]; 408 b2 = binaryData[dataIndex++]; 409 b3 = binaryData[dataIndex++]; 410 411 412 l = (byte)(b2 & 0x0f); 413 k = (byte)(b1 & 0x03); 414 415 byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); 416 417 byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); 418 byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); 419 420 421 encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; 422 encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; 423 encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; 424 encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; 425 426 i++; 427 } 428 encodedData[encodedIndex++] = 0xa; 429 } 430 431 for (; i<numberTriplets; i++) { 432 b1 = binaryData[dataIndex++]; 433 b2 = binaryData[dataIndex++]; 434 b3 = binaryData[dataIndex++]; 435 436 437 l = (byte)(b2 & 0x0f); 438 k = (byte)(b1 & 0x03); 439 440 byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); 441 442 byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); 443 byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); 444 445 446 encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; 447 encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; 448 encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; 449 encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; 450 } 451 452 // form integral number of 6-bit groups 453 if (fewerThan24bits == EIGHTBIT) { 454 b1 = binaryData[dataIndex]; 455 k = (byte) ( b1 &0x03 ); 456 byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); 457 encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; 458 encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ]; 459 encodedData[encodedIndex++] = PAD; 460 encodedData[encodedIndex++] = PAD; 461 } else if (fewerThan24bits == SIXTEENBIT) { 462 b1 = binaryData[dataIndex]; 463 b2 = binaryData[dataIndex +1 ]; 464 l = ( byte ) ( b2 &0x0f ); 465 k = ( byte ) ( b1 &0x03 ); 466 467 byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); 468 byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); 469 470 encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; 471 encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; 472 encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ]; 473 encodedData[encodedIndex++] = PAD; 474 } 475 476 //encodedData[encodedIndex] = 0xa; 477 478 return new String(encodedData); 479 } 480 481 /** 482 * Decodes Base64 data into octects 483 * 484 * @param encoded String containing base64 encoded data 485 * @return byte array containing the decoded data 486 * @throws Base64DecodingException if there is a problem decoding the data 487 */ 488 public final static byte[] decode(String encoded) throws Base64DecodingException { 489 490 if (encoded == null) 491 return null; 492 byte []bytes=new byte[encoded.length()]; 493 int len=getBytesInternal(encoded, bytes); 494 return decodeInternal(bytes, len); 495 } 496 497 protected static final int getBytesInternal(String s,byte[] result) { 498 int length=s.length(); 499 500 int newSize=0; 501 for (int i = 0; i < length; i++) { 502 byte dataS=(byte)s.charAt(i); 503 if (!isWhiteSpace(dataS)) 504 result[newSize++] = dataS; 505 } 506 return newSize; 507 508 } 509 protected final static byte[] decodeInternal(byte[] base64Data, int len) throws Base64DecodingException { 510 // remove white spaces 511 if (len==-1) 512 len = removeWhiteSpace(base64Data); 513 514 if (len%FOURBYTE != 0) { 515 throw new Base64DecodingException("decoding.divisible.four"); 516 //should be divisible by four 517 } 518 519 int numberQuadruple = (len/FOURBYTE ); 520 521 if (numberQuadruple == 0) 522 return new byte[0]; 523 524 byte decodedData[] = null; 525 byte b1=0,b2=0,b3=0, b4=0; 526 527 528 int i = 0; 529 int encodedIndex = 0; 530 int dataIndex = 0; 531 532 //decodedData = new byte[ (numberQuadruple)*3]; 533 dataIndex=(numberQuadruple-1)*4; 534 encodedIndex=(numberQuadruple-1)*3; 535 //first last bits. 536 b1 = base64Alphabet[base64Data[dataIndex++]]; 537 b2 = base64Alphabet[base64Data[dataIndex++]]; 538 if ((b1==-1) || (b2==-1)) { 539 throw new Base64DecodingException("decoding.general");//if found "no data" just return null 540 } 541 542 543 byte d3,d4; 544 b3 = base64Alphabet[d3=base64Data[dataIndex++]]; 545 b4 = base64Alphabet[d4=base64Data[dataIndex++]]; 546 if ((b3==-1 ) || (b4==-1) ) { 547 //Check if they are PAD characters 548 if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] 549 if ((b2 & 0xf) != 0)//last 4 bits should be zero 550 throw new Base64DecodingException("decoding.general"); 551 decodedData = new byte[ encodedIndex + 1 ]; 552 decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; 553 } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] 554 if ((b3 & 0x3 ) != 0)//last 2 bits should be zero 555 throw new Base64DecodingException("decoding.general"); 556 decodedData = new byte[ encodedIndex + 2 ]; 557 decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ); 558 decodedData[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); 559 } else { 560 throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data 561 } 562 } else { 563 //No PAD e.g 3cQl 564 decodedData = new byte[encodedIndex+3]; 565 decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; 566 decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); 567 decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); 568 } 569 encodedIndex=0; 570 dataIndex=0; 571 //the begin 572 for (i=numberQuadruple-1; i>0; i--) { 573 b1 = base64Alphabet[base64Data[dataIndex++]]; 574 b2 = base64Alphabet[base64Data[dataIndex++]]; 575 b3 = base64Alphabet[base64Data[dataIndex++]]; 576 b4 = base64Alphabet[base64Data[dataIndex++]]; 577 578 if ( (b1==-1) || 579 (b2==-1) || 580 (b3==-1) || 581 (b4==-1) ) { 582 throw new Base64DecodingException("decoding.general");//if found "no data" just return null 583 } 584 585 decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; 586 decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); 587 decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); 588 } 589 return decodedData; 590 } 591 /** 592 * Decodes Base64 data into outputstream 593 * 594 * @param base64Data String containing Base64 data 595 * @param os the outputstream 596 * @throws IOException 597 * @throws Base64DecodingException 598 */ 599 public final static void decode(String base64Data, 600 OutputStream os) throws Base64DecodingException, IOException { 601 byte[] bytes=new byte[base64Data.length()]; 602 int len=getBytesInternal(base64Data, bytes); 603 decode(bytes,os,len); 604 } 605 /** 606 * Decodes Base64 data into outputstream 607 * 608 * @param base64Data Byte array containing Base64 data 609 * @param os the outputstream 610 * @throws IOException 611 * @throws Base64DecodingException 612 */ 613 public final static void decode(byte[] base64Data, 614 OutputStream os) throws Base64DecodingException, IOException { 615 decode(base64Data,os,-1); 616 } 617 protected final static void decode(byte[] base64Data, 618 OutputStream os,int len) throws Base64DecodingException, IOException { 619 620 // remove white spaces 621 if (len==-1) 622 len = removeWhiteSpace(base64Data); 623 624 if (len%FOURBYTE != 0) { 625 throw new Base64DecodingException("decoding.divisible.four"); 626 //should be divisible by four 627 } 628 629 int numberQuadruple = (len/FOURBYTE ); 630 631 if (numberQuadruple == 0) 632 return; 633 634 //byte decodedData[] = null; 635 byte b1=0,b2=0,b3=0, b4=0; 636 637 int i = 0; 638 639 int dataIndex = 0; 640 641 //the begin 642 for (i=numberQuadruple-1; i>0; i--) { 643 b1 = base64Alphabet[base64Data[dataIndex++]]; 644 b2 = base64Alphabet[base64Data[dataIndex++]]; 645 b3 = base64Alphabet[base64Data[dataIndex++]]; 646 b4 = base64Alphabet[base64Data[dataIndex++]]; 647 if ( (b1==-1) || 648 (b2==-1) || 649 (b3==-1) || 650 (b4==-1) ) 651 throw new Base64DecodingException("decoding.general");//if found "no data" just return null 652 653 654 655 os.write((byte)( b1 <<2 | b2>>4 ) ); 656 os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); 657 os.write( (byte)( b3<<6 | b4 )); 658 } 659 b1 = base64Alphabet[base64Data[dataIndex++]]; 660 b2 = base64Alphabet[base64Data[dataIndex++]]; 661 662 // first last bits. 663 if ((b1==-1) || 664 (b2==-1) ){ 665 throw new Base64DecodingException("decoding.general");//if found "no data" just return null 666 } 667 668 byte d3,d4; 669 b3= base64Alphabet[d3 = base64Data[dataIndex++]]; 670 b4= base64Alphabet[d4 = base64Data[dataIndex++]]; 671 if ((b3==-1 ) || 672 (b4==-1) ) {//Check if they are PAD characters 673 if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] 674 if ((b2 & 0xf) != 0)//last 4 bits should be zero 675 throw new Base64DecodingException("decoding.general"); 676 os.write( (byte)( b1 <<2 | b2>>4 ) ); 677 } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] 678 if ((b3 & 0x3 ) != 0)//last 2 bits should be zero 679 throw new Base64DecodingException("decoding.general"); 680 os.write( (byte)( b1 <<2 | b2>>4 )); 681 os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); 682 } else { 683 throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data 684 } 685 } else { 686 //No PAD e.g 3cQl 687 os.write((byte)( b1 <<2 | b2>>4 ) ); 688 os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); 689 os.write((byte)( b3<<6 | b4 )); 690 } 691 return ; 692 } 693 694 /** 695 * Decodes Base64 data into outputstream 696 * 697 * @param is containing Base64 data 698 * @param os the outputstream 699 * @throws IOException 700 * @throws Base64DecodingException 701 */ 702 public final static void decode(InputStream is, 703 OutputStream os) throws Base64DecodingException, IOException { 704 //byte decodedData[] = null; 705 byte b1=0,b2=0,b3=0, b4=0; 706 707 int index=0; 708 byte []data=new byte[4]; 709 int read; 710 //the begin 711 while ((read=is.read())>0) { 712 byte readed=(byte)read; 713 if (isWhiteSpace(readed)) { 714 continue; 715 } 716 if (isPad(readed)) { 717 data[index++]=readed; 718 if (index==3) 719 data[index++]=(byte)is.read(); 720 break; 721 } 722 723 724 if ((data[index++]=readed)==-1) { 725 throw new Base64DecodingException("decoding.general");//if found "no data" just return null 726 } 727 728 if (index!=4) { 729 continue; 730 } 731 index=0; 732 b1 = base64Alphabet[data[0]]; 733 b2 = base64Alphabet[data[1]]; 734 b3 = base64Alphabet[data[2]]; 735 b4 = base64Alphabet[data[3]]; 736 737 os.write((byte)( b1 <<2 | b2>>4 ) ); 738 os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); 739 os.write( (byte)( b3<<6 | b4 )); 740 } 741 742 743 byte d1=data[0],d2=data[1],d3=data[2], d4=data[3]; 744 b1 = base64Alphabet[d1]; 745 b2 = base64Alphabet[d2]; 746 b3 = base64Alphabet[ d3 ]; 747 b4 = base64Alphabet[ d4 ]; 748 if ((b3==-1 ) || 749 (b4==-1) ) {//Check if they are PAD characters 750 if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] 751 if ((b2 & 0xf) != 0)//last 4 bits should be zero 752 throw new Base64DecodingException("decoding.general"); 753 os.write( (byte)( b1 <<2 | b2>>4 ) ); 754 } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] 755 b3 = base64Alphabet[ d3 ]; 756 if ((b3 & 0x3 ) != 0)//last 2 bits should be zero 757 throw new Base64DecodingException("decoding.general"); 758 os.write( (byte)( b1 <<2 | b2>>4 )); 759 os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); 760 } else { 761 throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data 762 } 763 } else { 764 //No PAD e.g 3cQl 765 766 os.write((byte)( b1 <<2 | b2>>4 ) ); 767 os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); 768 os.write((byte)( b3<<6 | b4 )); 769 } 770 771 return ; 772 } 773 /** 774 * remove WhiteSpace from MIME containing encoded Base64 data. 775 * 776 * @param data the byte array of base64 data (with WS) 777 * @return the new length 778 */ 779 protected static final int removeWhiteSpace(byte[] data) { 780 if (data == null) 781 return 0; 782 783 // count characters that's not whitespace 784 int newSize = 0; 785 int len = data.length; 786 for (int i = 0; i < len; i++) { 787 byte dataS=data[i]; 788 if (!isWhiteSpace(dataS)) 789 data[newSize++] = dataS; 790 } 791 return newSize; 792 } 793 }