1 /*
   2  * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /**
  25  * @test 4235519 8004212 8005394 8007298 8006295 8006315 8006530
  26  * @summary tests java.util.Base64
  27  */
  28 
  29 import java.io.ByteArrayInputStream;
  30 import java.io.ByteArrayOutputStream;
  31 import java.io.InputStream;
  32 import java.io.IOException;
  33 import java.io.OutputStream;
  34 import java.nio.ByteBuffer;
  35 import java.util.Arrays;
  36 import java.util.Base64;
  37 import java.util.Random;
  38 
  39 public class TestBase64 {
  40 
  41     public static void main(String args[]) throws Throwable {
  42         int numRuns  = 10;
  43         int numBytes = 200;
  44         if (args.length > 1) {
  45             numRuns  = Integer.parseInt(args[0]);
  46             numBytes = Integer.parseInt(args[1]);
  47         }
  48 
  49         test(Base64.getEncoder(),     Base64.getDecoder(),
  50              numRuns, numBytes);
  51         test(Base64.getUrlEncoder(),  Base64.getUrlDecoder(),
  52              numRuns, numBytes);
  53         test(Base64.getMimeEncoder(), Base64.getMimeDecoder(),
  54              numRuns, numBytes);
  55 
  56         Random rnd = new java.util.Random();
  57         byte[] nl_1 = new byte[] {'\n'};
  58         byte[] nl_2 = new byte[] {'\n', '\r'};
  59         byte[] nl_3 = new byte[] {'\n', '\r', '\n'};
  60         for (int i = 0; i < 10; i++) {
  61             int len = rnd.nextInt(200) + 4;
  62             test(Base64.getEncoder(len, nl_1),
  63                  Base64.getMimeDecoder(),
  64                  numRuns, numBytes);
  65             test(Base64.getEncoder(len, nl_2),
  66                  Base64.getMimeDecoder(),
  67                  numRuns, numBytes);
  68             test(Base64.getEncoder(len, nl_3),
  69                  Base64.getMimeDecoder(),
  70                  numRuns, numBytes);
  71         }
  72 
  73         testNull(Base64.getEncoder());
  74         testNull(Base64.getUrlEncoder());
  75         testNull(Base64.getMimeEncoder());
  76         testNull(Base64.getEncoder(10, new byte[]{'\n'}));
  77         testNull(Base64.getDecoder());
  78         testNull(Base64.getUrlDecoder());
  79         testNull(Base64.getMimeDecoder());
  80         checkNull(new Runnable() { public void run() { Base64.getEncoder(10, null); }});
  81 
  82         testIOE(Base64.getEncoder());
  83         testIOE(Base64.getUrlEncoder());
  84         testIOE(Base64.getMimeEncoder());
  85         testIOE(Base64.getEncoder(10, new byte[]{'\n'}));
  86 
  87         byte[] src = new byte[1024];
  88         new Random().nextBytes(src);
  89         final byte[] decoded = Base64.getEncoder().encode(src);
  90         testIOE(Base64.getDecoder(), decoded);
  91         testIOE(Base64.getMimeDecoder(), decoded);
  92         testIOE(Base64.getUrlDecoder(), Base64.getUrlEncoder().encode(src));
  93 
  94         // illegal line separator
  95         checkIAE(new Runnable() { public void run() { Base64.getEncoder(10, new byte[]{'\r', 'N'}); }});
  96 
  97         // illegal base64 character
  98         decoded[2] = (byte)0xe0;
  99         checkIAE(new Runnable() {
 100             public void run() { Base64.getDecoder().decode(decoded); }});
 101         checkIAE(new Runnable() {
 102             public void run() { Base64.getDecoder().decode(decoded, new byte[1024]); }});
 103         checkIAE(new Runnable() { public void run() {
 104             Base64.getDecoder().decode(ByteBuffer.wrap(decoded)); }});
 105         checkIAE(new Runnable() { public void run() {
 106             Base64.getDecoder().decode(ByteBuffer.wrap(decoded), ByteBuffer.allocate(1024)); }});
 107         checkIAE(new Runnable() { public void run() {
 108             Base64.getDecoder().decode(ByteBuffer.wrap(decoded), ByteBuffer.allocateDirect(1024)); }});
 109 
 110         // test return value from decode(ByteBuffer, ByteBuffer)
 111         testDecBufRet();
 112 
 113         // test single-non-base64 character for mime decoding
 114         testSingleNonBase64MimeDec();
 115 
 116         // test decoding of unpadded data
 117         testDecodeUnpadded();
 118 
 119         // test mime decoding with ignored character after padding
 120         testDecodeIgnoredAfterPadding();
 121     }
 122 
 123     private static sun.misc.BASE64Encoder sunmisc = new sun.misc.BASE64Encoder();
 124 
 125     private static void test(Base64.Encoder enc, Base64.Decoder dec,
 126                              int numRuns, int numBytes) throws Throwable {
 127         Random rnd = new java.util.Random();
 128 
 129         enc.encode(new byte[0]);
 130         dec.decode(new byte[0]);
 131 
 132         for (int i=0; i<numRuns; i++) {
 133             for (int j=1; j<numBytes; j++) {
 134                 byte[] orig = new byte[j];
 135                 rnd.nextBytes(orig);
 136 
 137                 // --------testing encode/decode(byte[])--------
 138                 byte[] encoded = enc.encode(orig);
 139                 byte[] decoded = dec.decode(encoded);
 140 
 141                 checkEqual(orig, decoded,
 142                            "Base64 array encoding/decoding failed!");
 143 
 144                 // compare to sun.misc.BASE64Encoder
 145                 byte[] encoded2 = sunmisc.encode(orig).getBytes("ASCII");
 146                 checkEqual(normalize(encoded),
 147                            normalize(encoded2),
 148                            "Base64 enc.encode() does not match sun.misc.base64!");
 149 
 150                 // remove padding '=' to test non-padding decoding case
 151                 if (encoded[encoded.length -2] == '=')
 152                     encoded2 = Arrays.copyOf(encoded,  encoded.length -2);
 153                 else if (encoded[encoded.length -1] == '=')
 154                     encoded2 = Arrays.copyOf(encoded, encoded.length -1);
 155                 else
 156                     encoded2 = null;
 157 
 158                 // --------testing encodetoString(byte[])/decode(String)--------
 159                 String str = enc.encodeToString(orig);
 160                 if (!Arrays.equals(str.getBytes("ASCII"), encoded)) {
 161                     throw new RuntimeException(
 162                         "Base64 encodingToString() failed!");
 163                 }
 164                 byte[] buf = dec.decode(new String(encoded, "ASCII"));
 165                 checkEqual(buf, orig, "Base64 decoding(String) failed!");
 166 
 167                 if (encoded2 != null) {
 168                     buf = dec.decode(new String(encoded2, "ASCII"));
 169                     checkEqual(buf, orig, "Base64 decoding(String) failed!");
 170                 }
 171 
 172                 //-------- testing encode/decode(Buffer)--------
 173                 testEncode(enc, ByteBuffer.wrap(orig), encoded);
 174                 ByteBuffer bin = ByteBuffer.allocateDirect(orig.length);
 175                 bin.put(orig).flip();
 176                 testEncode(enc, bin, encoded);
 177 
 178                 testDecode(dec, ByteBuffer.wrap(encoded), orig);
 179                 bin = ByteBuffer.allocateDirect(encoded.length);
 180                 bin.put(encoded).flip();
 181                 testDecode(dec, bin, orig);
 182 
 183                 if (encoded2 != null)
 184                     testDecode(dec, ByteBuffer.wrap(encoded2), orig);
 185 
 186                 // -------- testing encode(Buffer, Buffer)--------
 187                 testEncode(enc, encoded,
 188                            ByteBuffer.wrap(orig),
 189                            ByteBuffer.allocate(encoded.length + 10));
 190 
 191                 testEncode(enc, encoded,
 192                            ByteBuffer.wrap(orig),
 193                            ByteBuffer.allocateDirect(encoded.length + 10));
 194 
 195                 // --------testing decode(Buffer, Buffer);--------
 196                 testDecode(dec, orig,
 197                            ByteBuffer.wrap(encoded),
 198                            ByteBuffer.allocate(orig.length + 10));
 199 
 200                 testDecode(dec, orig,
 201                            ByteBuffer.wrap(encoded),
 202                            ByteBuffer.allocateDirect(orig.length + 10));
 203 
 204                 // --------testing decode.wrap(input stream)--------
 205                 // 1) random buf length
 206                 ByteArrayInputStream bais = new ByteArrayInputStream(encoded);
 207                 InputStream is = dec.wrap(bais);
 208                 buf = new byte[orig.length + 10];
 209                 int len = orig.length;
 210                 int off = 0;
 211                 while (true) {
 212                     int n = rnd.nextInt(len);
 213                     if (n == 0)
 214                         n = 1;
 215                     n = is.read(buf, off, n);
 216                     if (n == -1) {
 217                         checkEqual(off, orig.length,
 218                                    "Base64 stream decoding failed");
 219                         break;
 220                     }
 221                     off += n;
 222                     len -= n;
 223                     if (len == 0)
 224                         break;
 225                 }
 226                 buf = Arrays.copyOf(buf, off);
 227                 checkEqual(buf, orig, "Base64 stream decoding failed!");
 228 
 229                 // 2) read one byte each
 230                 bais.reset();
 231                 is = dec.wrap(bais);
 232                 buf = new byte[orig.length + 10];
 233                 off = 0;
 234                 int b;
 235                 while ((b = is.read()) != -1) {
 236                     buf[off++] = (byte)b;
 237                 }
 238                 buf = Arrays.copyOf(buf, off);
 239                 checkEqual(buf, orig, "Base64 stream decoding failed!");
 240 
 241                 // --------testing encode.wrap(output stream)--------
 242                 ByteArrayOutputStream baos = new ByteArrayOutputStream((orig.length + 2) / 3 * 4 + 10);
 243                 OutputStream os = enc.wrap(baos);
 244                 off = 0;
 245                 len = orig.length;
 246                 for (int k = 0; k < 5; k++) {
 247                     if (len == 0)
 248                         break;
 249                     int n = rnd.nextInt(len);
 250                     if (n == 0)
 251                         n = 1;
 252                     os.write(orig, off, n);
 253                     off += n;
 254                     len -= n;
 255                 }
 256                 if (len != 0)
 257                     os.write(orig, off, len);
 258                 os.close();
 259                 buf = baos.toByteArray();
 260                 checkEqual(buf, encoded, "Base64 stream encoding failed!");
 261 
 262                 // 2) write one byte each
 263                 baos.reset();
 264                 os = enc.wrap(baos);
 265                 off = 0;
 266                 while (off < orig.length) {
 267                     os.write(orig[off++]);
 268                 }
 269                 os.close();
 270                 buf = baos.toByteArray();
 271                 checkEqual(buf, encoded, "Base64 stream encoding failed!");
 272 
 273                 // --------testing encode(in, out); -> bigger buf--------
 274                 buf = new byte[encoded.length + rnd.nextInt(100)];
 275                 int ret = enc.encode(orig, buf);
 276                 checkEqual(ret, encoded.length,
 277                            "Base64 enc.encode(src, null) returns wrong size!");
 278                 buf = Arrays.copyOf(buf, ret);
 279                 checkEqual(buf, encoded,
 280                            "Base64 enc.encode(src, dst) failed!");
 281 
 282                 // --------testing decode(in, out); -> bigger buf--------
 283                 buf = new byte[orig.length + rnd.nextInt(100)];
 284                 ret = dec.decode(encoded, buf);
 285                 checkEqual(ret, orig.length,
 286                           "Base64 enc.encode(src, null) returns wrong size!");
 287                 buf = Arrays.copyOf(buf, ret);
 288                 checkEqual(buf, orig,
 289                            "Base64 dec.decode(src, dst) failed!");
 290 
 291             }
 292         }
 293     }
 294 
 295     private static final byte[] ba_null = null;
 296     private static final String str_null = null;
 297     private static final ByteBuffer bb_null = null;
 298 
 299     private static void testNull(final Base64.Encoder enc) {
 300         checkNull(new Runnable() { public void run() { enc.encode(ba_null); }});
 301         checkNull(new Runnable() { public void run() { enc.encodeToString(ba_null); }});
 302         checkNull(new Runnable() { public void run() { enc.encode(ba_null, new byte[10]); }});
 303         checkNull(new Runnable() { public void run() { enc.encode(new byte[10], ba_null); }});
 304         checkNull(new Runnable() { public void run() { enc.encode(bb_null); }});
 305         checkNull(new Runnable() { public void run() { enc.encode(bb_null, ByteBuffer.allocate(10), 0); }});
 306         checkNull(new Runnable() { public void run() { enc.encode(ByteBuffer.allocate(10), bb_null, 0); }});
 307         checkNull(new Runnable() { public void run() { enc.wrap(null); }});
 308     }
 309 
 310     private static void testNull(final Base64.Decoder dec) {
 311         checkNull(new Runnable() { public void run() { dec.decode(ba_null); }});
 312         checkNull(new Runnable() { public void run() { dec.decode(str_null); }});
 313         checkNull(new Runnable() { public void run() { dec.decode(ba_null, new byte[10]); }});
 314         checkNull(new Runnable() { public void run() { dec.decode(new byte[10], ba_null); }});
 315         checkNull(new Runnable() { public void run() { dec.decode(bb_null); }});
 316         checkNull(new Runnable() { public void run() { dec.decode(bb_null, ByteBuffer.allocate(10)); }});
 317         checkNull(new Runnable() { public void run() { dec.decode(ByteBuffer.allocate(10), bb_null); }});
 318         checkNull(new Runnable() { public void run() { dec.wrap(null); }});
 319     }
 320 
 321     private static interface Testable {
 322         public void test() throws Throwable;
 323     }
 324 
 325     private static void testIOE(final Base64.Encoder enc) throws Throwable {
 326         ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
 327         final OutputStream os = enc.wrap(baos);
 328         os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});
 329         os.close();
 330         checkIOE(new Testable() { public void test() throws Throwable { os.write(10); }});
 331         checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}); }});
 332         checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}, 1, 4); }});
 333     }
 334 
 335     private static void testIOE(final Base64.Decoder dec, byte[] decoded) throws Throwable {
 336         ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
 337         final InputStream is = dec.wrap(bais);
 338         is.read(new byte[10]);
 339         is.close();
 340         checkIOE(new Testable() { public void test() throws Throwable { is.read(); }});
 341         checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}); }});
 342         checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}, 1, 4); }});
 343         checkIOE(new Testable() { public void test() throws Throwable { is.available(); }});
 344         checkIOE(new Testable() { public void test() throws Throwable { is.skip(20); }});
 345     }
 346 
 347     private static final void checkNull(Runnable r) {
 348         try {
 349             r.run();
 350             throw new RuntimeException("NPE is not thrown as expected");
 351         } catch (NullPointerException npe) {}
 352     }
 353 
 354     private static final void checkIOE(Testable t) throws Throwable {
 355         try {
 356             t.test();
 357             throw new RuntimeException("IOE is not thrown as expected");
 358         } catch (IOException ioe) {}
 359     }
 360 
 361     private static final void checkIAE(Runnable r) throws Throwable {
 362         try {
 363             r.run();
 364             throw new RuntimeException("IAE is not thrown as expected");
 365         } catch (IllegalArgumentException iae) {}
 366     }
 367 
 368     private static void testDecodeIgnoredAfterPadding() throws Throwable {
 369         for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {
 370             byte[][] src = new byte[][] {
 371                 "A".getBytes("ascii"),
 372                 "AB".getBytes("ascii"),
 373                 "ABC".getBytes("ascii"),
 374                 "ABCD".getBytes("ascii"),
 375                 "ABCDE".getBytes("ascii")
 376             };
 377             Base64.Encoder encM = Base64.getMimeEncoder();
 378             Base64.Decoder decM = Base64.getMimeDecoder();
 379             Base64.Encoder enc = Base64.getEncoder();
 380             Base64.Decoder dec = Base64.getDecoder();
 381             for (int i = 0; i < src.length; i++) {
 382                 // decode(byte[])
 383                 byte[] encoded = encM.encode(src[i]);
 384                 encoded = Arrays.copyOf(encoded, encoded.length + 1);
 385                 encoded[encoded.length - 1] = nonBase64;
 386                 checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");
 387                 try {
 388                     dec.decode(encoded);
 389                     throw new RuntimeException("No IAE for non-base64 char");
 390                 } catch (IllegalArgumentException iae) {}
 391 
 392                 // decode(ByteBuffer[], ByteBuffer[])
 393                 ByteBuffer encodedBB = ByteBuffer.wrap(encoded);
 394                 ByteBuffer decodedBB = ByteBuffer.allocate(100);
 395                 int ret = decM.decode(encodedBB, decodedBB);
 396                 byte[] buf = new byte[ret];
 397                 decodedBB.flip();
 398                 decodedBB.get(buf);
 399                 checkEqual(buf, src[i], "Non-base64 char is not ignored");
 400                 try {
 401                     encodedBB.rewind();
 402                     decodedBB.clear();
 403                     dec.decode(encodedBB, decodedBB);
 404                     throw new RuntimeException("No IAE for non-base64 char");
 405                 } catch (IllegalArgumentException iae) {}
 406                 // direct
 407                 encodedBB.rewind();
 408                 decodedBB = ByteBuffer.allocateDirect(100);
 409                 ret = decM.decode(encodedBB, decodedBB);
 410                 buf = new byte[ret];
 411                 decodedBB.flip();
 412                 decodedBB.get(buf);
 413                 checkEqual(buf, src[i], "Non-base64 char is not ignored");
 414                 try {
 415                     encodedBB.rewind();
 416                     decodedBB.clear();
 417                     dec.decode(encodedBB, decodedBB);
 418                     throw new RuntimeException("No IAE for non-base64 char");
 419                 } catch (IllegalArgumentException iae) {}
 420             }
 421         }
 422     }
 423         
 424     private static void  testDecodeUnpadded() throws Throwable {
 425         byte[] srcA = new byte[] { 'Q', 'Q' };
 426         byte[] srcAA = new byte[] { 'Q', 'Q', 'E'};
 427         Base64.Decoder dec = Base64.getDecoder();
 428         byte[] ret = dec.decode(srcA);
 429         if (ret[0] != 'A')
 430             throw new RuntimeException("Decoding unpadding input A failed");
 431         ret = dec.decode(srcAA);
 432         if (ret[0] != 'A' && ret[1] != 'A')
 433             throw new RuntimeException("Decoding unpadding input AA failed");
 434         ret = new byte[10];
 435         if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 1 &&
 436             ret[0] != 'A')           
 437             throw new RuntimeException("Decoding unpadding input A from stream failed");
 438         if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 2 &&
 439             ret[0] != 'A' && ret[1] != 'A')           
 440             throw new RuntimeException("Decoding unpadding input AA from stream failed");
 441     }
 442 
 443     // single-non-base64-char should be ignored for mime decoding, but
 444     // iae for basic decoding
 445     private static void testSingleNonBase64MimeDec() throws Throwable {
 446         for (String nonBase64 : new String[] {"#", "(", "!", "\\", "-", "_"}) {
 447             if (Base64.getMimeDecoder().decode(nonBase64).length != 0) {
 448                 throw new RuntimeException("non-base64 char is not ignored");
 449             }
 450             try {
 451                 Base64.getDecoder().decode(nonBase64);
 452                 throw new RuntimeException("No IAE for single non-base64 char");
 453             } catch (IllegalArgumentException iae) {}
 454         }
 455     }
 456 
 457     private static void testDecBufRet() throws Throwable {
 458         Random rnd = new java.util.Random();
 459         Base64.Encoder encoder = Base64.getEncoder();
 460         Base64.Decoder decoder = Base64.getDecoder();
 461         //                src   pos, len  expected
 462         int[][] tests = { { 6,    3,   3,   3},   // xxx xxx    -> yyyy yyyy
 463                           { 6,    3,   4,   3},
 464                           { 6,    3,   5,   3},
 465                           { 6,    3,   6,   6},
 466                           { 6,   11,   4,   3},
 467                           { 6,   11,   4,   3},
 468                           { 6,   11,   5,   3},
 469                           { 6,   11,   6,   6},
 470                           { 7,    3,   6,   6},   // xxx xxx x  -> yyyy yyyy yy==
 471                           { 7,    3,   7,   7},
 472                           { 7,   11,   6,   6},
 473                           { 7,   11,   7,   7},
 474                           { 8,    3,   6,   6},   // xxx xxx xx -> yyyy yyyy yyy=
 475                           { 8,    3,   7,   6},
 476                           { 8,    3,   8,   8},
 477                           { 8,   13,   6,   6},
 478                           { 8,   13,   7,   6},
 479                           { 8,   13,   8,   8},
 480 
 481         };
 482         ByteBuffer dstBuf = ByteBuffer.allocate(100);
 483         for (boolean direct : new boolean[] { false, true}) {
 484             for (int[] test : tests) {
 485                 byte[] src = new byte[test[0]];
 486                 rnd.nextBytes(src);
 487                 ByteBuffer srcBuf = direct ? ByteBuffer.allocate(100)
 488                                            : ByteBuffer.allocateDirect(100);
 489                 srcBuf.put(encoder.encode(src)).flip();
 490                 dstBuf.clear().position(test[1]).limit(test[1]+ test[2]);
 491                 int ret = decoder.decode(srcBuf, dstBuf);
 492                 if (ret != test[3]) {
 493                     System.out.printf(" [%6s] src=%d, pos=%d, len=%d, expected=%d, ret=%d%n",
 494                                       direct?"direct":"",
 495                                       test[0], test[1], test[2], test[3], ret);
 496                     throw new RuntimeException("ret != expected");
 497                 }
 498             }
 499         }
 500     }
 501 
 502     private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected)
 503         throws Throwable {
 504 
 505         ByteBuffer bout = enc.encode(bin);
 506         byte[] buf = new byte[bout.remaining()];
 507         bout.get(buf);
 508         if (bin.hasRemaining()) {
 509             throw new RuntimeException(
 510                 "Base64 enc.encode(ByteBuffer) failed!");
 511         }
 512         checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
 513     }
 514 
 515     private static final void testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)
 516         throws Throwable {
 517 
 518         ByteBuffer bout = dec.decode(bin);
 519         byte[] buf = new byte[bout.remaining()];
 520         bout.get(buf);
 521         checkEqual(buf, expected, "Base64 dec.decode(bf) failed!");
 522     }
 523 
 524     private static final void testEncode(Base64.Encoder enc, byte[] expected,
 525                                          ByteBuffer ibb, ByteBuffer obb)
 526         throws Throwable {
 527         Random rnd = new Random();
 528         int bytesOut = enc.encode(ibb, obb, 0);
 529         if (ibb.hasRemaining()) {
 530             throw new RuntimeException(
 531                 "Base64 enc.encode(bf, bf) failed with wrong return!");
 532         }
 533         obb.flip();
 534         byte[] buf = new byte[obb.remaining()];
 535         obb.get(buf);
 536         checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
 537         ibb.rewind();
 538         obb.position(0);
 539         obb.limit(0);
 540         bytesOut = 0;
 541 
 542         do {  // increase the "limit" incrementally & randomly
 543             int n = rnd.nextInt(expected.length - obb.position());
 544             if (n == 0)
 545                 n = 1;
 546             obb.limit(obb.limit() + n);
 547             //obb.limit(Math.min(obb.limit() + n, expected.length));
 548             bytesOut = enc.encode(ibb, obb, bytesOut);
 549         } while (ibb.hasRemaining());
 550         obb.flip();
 551         buf = new byte[obb.remaining()];
 552         obb.get(buf);
 553         checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
 554     }
 555 
 556     private static final void testDecode(Base64.Decoder dec, byte[] expected,
 557                                          ByteBuffer ibb, ByteBuffer obb)
 558         throws Throwable {
 559         Random rnd = new Random();
 560 
 561         dec.decode(ibb, obb);
 562         if (ibb.hasRemaining()) {
 563             throw new RuntimeException(
 564                 "Base64 dec.decode(bf, bf) failed with un-decoded ibb!");
 565         }
 566         obb.flip();
 567         byte[] buf = new byte[obb.remaining()];
 568         obb.get(buf);
 569         checkEqual(buf, expected, "Base64 dec.decode(bf, bf) failed!");
 570 
 571         ibb.rewind();
 572         obb.position(0);
 573         obb.limit(0);
 574         do {  // increase the "limit" incrementally & randomly
 575             int n = rnd.nextInt(expected.length - obb.position());
 576             if (n == 0)
 577                 n = 1;
 578             obb.limit(obb.limit() + n);
 579             dec.decode(ibb, obb);
 580          } while (ibb.hasRemaining());
 581 
 582 
 583         obb.flip();
 584         buf = new byte[obb.remaining()];
 585         obb.get(buf);
 586         checkEqual(buf, expected, "Base64 dec.decode(bf, bf) failed!");
 587     }
 588 
 589     private static final void checkEqual(int v1, int v2, String msg)
 590         throws Throwable {
 591        if (v1 != v2) {
 592            System.out.printf("    v1=%d%n", v1);
 593            System.out.printf("    v2=%d%n", v2);
 594            throw new RuntimeException(msg);
 595        }
 596     }
 597 
 598     private static final void checkEqual(byte[] r1, byte[] r2, String msg)
 599         throws Throwable {
 600        if (!Arrays.equals(r1, r2)) {
 601            System.out.printf("    r1[%d]=[%s]%n", r1.length, new String(r1));
 602            System.out.printf("    r2[%d]=[%s]%n", r2.length, new String(r2));
 603            throw new RuntimeException(msg);
 604        }
 605     }
 606 
 607     // remove line feeds,
 608     private static final byte[] normalize(byte[] src) {
 609         int n = 0;
 610         boolean hasUrl = false;
 611         for (int i = 0; i < src.length; i++) {
 612             if (src[i] == '\r' || src[i] == '\n')
 613                 n++;
 614             if (src[i] == '-' || src[i] == '_')
 615                 hasUrl = true;
 616         }
 617         if (n == 0 && hasUrl == false)
 618             return src;
 619         byte[] ret = new byte[src.length - n];
 620         int j = 0;
 621         for (int i = 0; i < src.length; i++) {
 622             if (src[i] == '-')
 623                 ret[j++] = '+';
 624             else if (src[i] == '_')
 625                 ret[j++] = '/';
 626             else if (src[i] != '\r' && src[i] != '\n')
 627                 ret[j++] = src[i];
 628         }
 629         return ret;
 630     }
 631 }