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 8007379 8008925
  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         // illegal ending unit
 111         checkIAE(new Runnable() { public void run() { Base64.getMimeDecoder().decode("$=#"); }});
 112 
 113         // test return value from decode(ByteBuffer, ByteBuffer)
 114         testDecBufRet();
 115 
 116         // test single-non-base64 character for mime decoding
 117         testSingleNonBase64MimeDec();
 118 
 119         // test decoding of unpadded data
 120         testDecodeUnpadded();
 121         // test mime decoding with ignored character after padding
 122         testDecodeIgnoredAfterPadding();
 123     }
 124 
 125     private static sun.misc.BASE64Encoder sunmisc = new sun.misc.BASE64Encoder();
 126 
 127     private static void test(Base64.Encoder enc, Base64.Decoder dec,
 128                              int numRuns, int numBytes) throws Throwable {
 129         Random rnd = new java.util.Random();
 130 
 131         enc.encode(new byte[0]);
 132         dec.decode(new byte[0]);
 133 
 134         for (int i=0; i<numRuns; i++) {
 135             for (int j=1; j<numBytes; j++) {
 136                 byte[] orig = new byte[j];
 137                 rnd.nextBytes(orig);
 138 
 139                 // --------testing encode/decode(byte[])--------
 140                 byte[] encoded = enc.encode(orig);
 141                 byte[] decoded = dec.decode(encoded);
 142 
 143                 checkEqual(orig, decoded,
 144                            "Base64 array encoding/decoding failed!");
 145 
 146                 // compare to sun.misc.BASE64Encoder
 147                 byte[] encoded2 = sunmisc.encode(orig).getBytes("ASCII");
 148                 checkEqual(normalize(encoded),
 149                            normalize(encoded2),
 150                            "Base64 enc.encode() does not match sun.misc.base64!");
 151 
 152                 // remove padding '=' to test non-padding decoding case
 153                 if (encoded[encoded.length -2] == '=')
 154                     encoded2 = Arrays.copyOf(encoded,  encoded.length -2);
 155                 else if (encoded[encoded.length -1] == '=')
 156                     encoded2 = Arrays.copyOf(encoded, encoded.length -1);
 157                 else
 158                     encoded2 = null;
 159 
 160                 // --------testing encodetoString(byte[])/decode(String)--------
 161                 String str = enc.encodeToString(orig);
 162                 if (!Arrays.equals(str.getBytes("ASCII"), encoded)) {
 163                     throw new RuntimeException(
 164                         "Base64 encodingToString() failed!");
 165                 }
 166                 byte[] buf = dec.decode(new String(encoded, "ASCII"));
 167                 checkEqual(buf, orig, "Base64 decoding(String) failed!");
 168 
 169                 if (encoded2 != null) {
 170                     buf = dec.decode(new String(encoded2, "ASCII"));
 171                     checkEqual(buf, orig, "Base64 decoding(String) failed!");
 172                 }
 173 
 174                 //-------- testing encode/decode(Buffer)--------
 175                 testEncode(enc, ByteBuffer.wrap(orig), encoded);
 176                 ByteBuffer bin = ByteBuffer.allocateDirect(orig.length);
 177                 bin.put(orig).flip();
 178                 testEncode(enc, bin, encoded);
 179 
 180                 testDecode(dec, ByteBuffer.wrap(encoded), orig);
 181                 bin = ByteBuffer.allocateDirect(encoded.length);
 182                 bin.put(encoded).flip();
 183                 testDecode(dec, bin, orig);
 184 
 185                 if (encoded2 != null)
 186                     testDecode(dec, ByteBuffer.wrap(encoded2), orig);
 187 
 188                 // -------- testing encode(Buffer, Buffer)--------
 189                 testEncode(enc, encoded,
 190                            ByteBuffer.wrap(orig),
 191                            ByteBuffer.allocate(encoded.length + 10));
 192 
 193                 testEncode(enc, encoded,
 194                            ByteBuffer.wrap(orig),
 195                            ByteBuffer.allocateDirect(encoded.length + 10));
 196 
 197                 // --------testing decode(Buffer, Buffer);--------
 198                 testDecode(dec, orig,
 199                            ByteBuffer.wrap(encoded),
 200                            ByteBuffer.allocate(orig.length + 10));
 201 
 202                 testDecode(dec, orig,
 203                            ByteBuffer.wrap(encoded),
 204                            ByteBuffer.allocateDirect(orig.length + 10));
 205 
 206                 // --------testing decode.wrap(input stream)--------
 207                 // 1) random buf length
 208                 ByteArrayInputStream bais = new ByteArrayInputStream(encoded);
 209                 InputStream is = dec.wrap(bais);
 210                 buf = new byte[orig.length + 10];
 211                 int len = orig.length;
 212                 int off = 0;
 213                 while (true) {
 214                     int n = rnd.nextInt(len);
 215                     if (n == 0)
 216                         n = 1;
 217                     n = is.read(buf, off, n);
 218                     if (n == -1) {
 219                         checkEqual(off, orig.length,
 220                                    "Base64 stream decoding failed");
 221                         break;
 222                     }
 223                     off += n;
 224                     len -= n;
 225                     if (len == 0)
 226                         break;
 227                 }
 228                 buf = Arrays.copyOf(buf, off);
 229                 checkEqual(buf, orig, "Base64 stream decoding failed!");
 230 
 231                 // 2) read one byte each
 232                 bais.reset();
 233                 is = dec.wrap(bais);
 234                 buf = new byte[orig.length + 10];
 235                 off = 0;
 236                 int b;
 237                 while ((b = is.read()) != -1) {
 238                     buf[off++] = (byte)b;
 239                 }
 240                 buf = Arrays.copyOf(buf, off);
 241                 checkEqual(buf, orig, "Base64 stream decoding failed!");
 242 
 243                 // --------testing encode.wrap(output stream)--------
 244                 ByteArrayOutputStream baos = new ByteArrayOutputStream((orig.length + 2) / 3 * 4 + 10);
 245                 OutputStream os = enc.wrap(baos);
 246                 off = 0;
 247                 len = orig.length;
 248                 for (int k = 0; k < 5; k++) {
 249                     if (len == 0)
 250                         break;
 251                     int n = rnd.nextInt(len);
 252                     if (n == 0)
 253                         n = 1;
 254                     os.write(orig, off, n);
 255                     off += n;
 256                     len -= n;
 257                 }
 258                 if (len != 0)
 259                     os.write(orig, off, len);
 260                 os.close();
 261                 buf = baos.toByteArray();
 262                 checkEqual(buf, encoded, "Base64 stream encoding failed!");
 263 
 264                 // 2) write one byte each
 265                 baos.reset();
 266                 os = enc.wrap(baos);
 267                 off = 0;
 268                 while (off < orig.length) {
 269                     os.write(orig[off++]);
 270                 }
 271                 os.close();
 272                 buf = baos.toByteArray();
 273                 checkEqual(buf, encoded, "Base64 stream encoding failed!");
 274 
 275                 // --------testing encode(in, out); -> bigger buf--------
 276                 buf = new byte[encoded.length + rnd.nextInt(100)];
 277                 int ret = enc.encode(orig, buf);
 278                 checkEqual(ret, encoded.length,
 279                            "Base64 enc.encode(src, null) returns wrong size!");
 280                 buf = Arrays.copyOf(buf, ret);
 281                 checkEqual(buf, encoded,
 282                            "Base64 enc.encode(src, dst) failed!");
 283 
 284                 // --------testing decode(in, out); -> bigger buf--------
 285                 buf = new byte[orig.length + rnd.nextInt(100)];
 286                 ret = dec.decode(encoded, buf);
 287                 checkEqual(ret, orig.length,
 288                           "Base64 enc.encode(src, null) returns wrong size!");
 289                 buf = Arrays.copyOf(buf, ret);
 290                 checkEqual(buf, orig,
 291                            "Base64 dec.decode(src, dst) failed!");
 292 
 293             }
 294         }
 295     }
 296 
 297     private static final byte[] ba_null = null;
 298     private static final String str_null = null;
 299     private static final ByteBuffer bb_null = null;
 300 
 301     private static void testNull(final Base64.Encoder enc) {
 302         checkNull(new Runnable() { public void run() { enc.encode(ba_null); }});
 303         checkNull(new Runnable() { public void run() { enc.encodeToString(ba_null); }});
 304         checkNull(new Runnable() { public void run() { enc.encode(ba_null, new byte[10]); }});
 305         checkNull(new Runnable() { public void run() { enc.encode(new byte[10], ba_null); }});
 306         checkNull(new Runnable() { public void run() { enc.encode(bb_null); }});
 307         checkNull(new Runnable() { public void run() { enc.encode(bb_null, ByteBuffer.allocate(10), 0); }});
 308         checkNull(new Runnable() { public void run() { enc.encode(ByteBuffer.allocate(10), bb_null, 0); }});
 309         checkNull(new Runnable() { public void run() { enc.wrap(null); }});
 310     }
 311 
 312     private static void testNull(final Base64.Decoder dec) {
 313         checkNull(new Runnable() { public void run() { dec.decode(ba_null); }});
 314         checkNull(new Runnable() { public void run() { dec.decode(str_null); }});
 315         checkNull(new Runnable() { public void run() { dec.decode(ba_null, new byte[10]); }});
 316         checkNull(new Runnable() { public void run() { dec.decode(new byte[10], ba_null); }});
 317         checkNull(new Runnable() { public void run() { dec.decode(bb_null); }});
 318         checkNull(new Runnable() { public void run() { dec.decode(bb_null, ByteBuffer.allocate(10)); }});
 319         checkNull(new Runnable() { public void run() { dec.decode(ByteBuffer.allocate(10), bb_null); }});
 320         checkNull(new Runnable() { public void run() { dec.wrap(null); }});
 321     }
 322 
 323     private static interface Testable {
 324         public void test() throws Throwable;
 325     }
 326 
 327     private static void testIOE(final Base64.Encoder enc) throws Throwable {
 328         ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
 329         final OutputStream os = enc.wrap(baos);
 330         os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});
 331         os.close();
 332         checkIOE(new Testable() { public void test() throws Throwable { os.write(10); }});
 333         checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}); }});
 334         checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}, 1, 4); }});
 335     }
 336 
 337     private static void testIOE(final Base64.Decoder dec, byte[] decoded) throws Throwable {
 338         ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
 339         final InputStream is = dec.wrap(bais);
 340         is.read(new byte[10]);
 341         is.close();
 342         checkIOE(new Testable() { public void test() throws Throwable { is.read(); }});
 343         checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}); }});
 344         checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}, 1, 4); }});
 345         checkIOE(new Testable() { public void test() throws Throwable { is.available(); }});
 346         checkIOE(new Testable() { public void test() throws Throwable { is.skip(20); }});
 347     }
 348 
 349     private static final void checkNull(Runnable r) {
 350         try {
 351             r.run();
 352             throw new RuntimeException("NPE is not thrown as expected");
 353         } catch (NullPointerException npe) {}
 354     }
 355 
 356     private static final void checkIOE(Testable t) throws Throwable {
 357         try {
 358             t.test();
 359             throw new RuntimeException("IOE is not thrown as expected");
 360         } catch (IOException ioe) {}
 361     }
 362 
 363     private static final void checkIAE(Runnable r) throws Throwable {
 364         try {
 365             r.run();
 366             throw new RuntimeException("IAE is not thrown as expected");
 367         } catch (IllegalArgumentException iae) {}
 368     }
 369 
 370     private static void testDecodeIgnoredAfterPadding() throws Throwable {
 371         for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {
 372             byte[][] src = new byte[][] {
 373                 "A".getBytes("ascii"),
 374                 "AB".getBytes("ascii"),
 375                 "ABC".getBytes("ascii"),
 376                 "ABCD".getBytes("ascii"),
 377                 "ABCDE".getBytes("ascii")
 378             };
 379             Base64.Encoder encM = Base64.getMimeEncoder();
 380             Base64.Decoder decM = Base64.getMimeDecoder();
 381             Base64.Encoder enc = Base64.getEncoder();
 382             Base64.Decoder dec = Base64.getDecoder();
 383             for (int i = 0; i < src.length; i++) {
 384                 // decode(byte[])
 385                 byte[] encoded = encM.encode(src[i]);
 386                 encoded = Arrays.copyOf(encoded, encoded.length + 1);
 387                 encoded[encoded.length - 1] = nonBase64;
 388                 checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");
 389                 byte[] decoded = new byte[src[i].length];
 390                 decM.decode(encoded, decoded);
 391                 checkEqual(decoded, src[i], "Non-base64 char is not ignored");
 392 
 393                 try {
 394                     dec.decode(encoded);
 395                     throw new RuntimeException("No IAE for non-base64 char");
 396                 } catch (IllegalArgumentException iae) {}
 397 
 398                 // decode(ByteBuffer[], ByteBuffer[])
 399                 ByteBuffer encodedBB = ByteBuffer.wrap(encoded);
 400                 ByteBuffer decodedBB = ByteBuffer.allocate(100);
 401                 int ret = decM.decode(encodedBB, decodedBB);
 402                 byte[] buf = new byte[ret];
 403                 decodedBB.flip();
 404                 decodedBB.get(buf);
 405                 checkEqual(buf, src[i], "Non-base64 char is not ignored");
 406                 try {
 407                     encodedBB.rewind();
 408                     decodedBB.clear();
 409                     dec.decode(encodedBB, decodedBB);
 410                     throw new RuntimeException("No IAE for non-base64 char");
 411                 } catch (IllegalArgumentException iae) {}
 412                 // direct
 413                 encodedBB.rewind();
 414                 decodedBB = ByteBuffer.allocateDirect(100);
 415                 ret = decM.decode(encodedBB, decodedBB);
 416                 buf = new byte[ret];
 417                 decodedBB.flip();
 418                 decodedBB.get(buf);
 419                 checkEqual(buf, src[i], "Non-base64 char is not ignored");
 420                 try {
 421                     encodedBB.rewind();
 422                     decodedBB.clear();
 423                     dec.decode(encodedBB, decodedBB);
 424                     throw new RuntimeException("No IAE for non-base64 char");
 425                 } catch (IllegalArgumentException iae) {}
 426             }
 427         }
 428     }
 429 
 430     private static void  testDecodeUnpadded() throws Throwable {
 431         byte[] srcA = new byte[] { 'Q', 'Q' };
 432         byte[] srcAA = new byte[] { 'Q', 'Q', 'E'};
 433         Base64.Decoder dec = Base64.getDecoder();
 434         byte[] ret = dec.decode(srcA);
 435         if (ret[0] != 'A')
 436             throw new RuntimeException("Decoding unpadding input A failed");
 437         ret = dec.decode(srcAA);
 438         if (ret[0] != 'A' && ret[1] != 'A')
 439             throw new RuntimeException("Decoding unpadding input AA failed");
 440         ret = new byte[10];
 441         if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 1 &&
 442             ret[0] != 'A')
 443             throw new RuntimeException("Decoding unpadding input A from stream failed");
 444         if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 2 &&
 445             ret[0] != 'A' && ret[1] != 'A')
 446             throw new RuntimeException("Decoding unpadding input AA from stream failed");
 447     }
 448 
 449     // single-non-base64-char should be ignored for mime decoding, but
 450     // iae for basic decoding
 451     private static void testSingleNonBase64MimeDec() throws Throwable {
 452         for (String nonBase64 : new String[] {"#", "(", "!", "\\", "-", "_"}) {
 453             if (Base64.getMimeDecoder().decode(nonBase64).length != 0) {
 454                 throw new RuntimeException("non-base64 char is not ignored");
 455             }
 456             try {
 457                 Base64.getDecoder().decode(nonBase64);
 458                 throw new RuntimeException("No IAE for single non-base64 char");
 459             } catch (IllegalArgumentException iae) {}
 460         }
 461     }
 462 
 463     private static void testDecBufRet() throws Throwable {
 464         Random rnd = new java.util.Random();
 465         Base64.Encoder encoder = Base64.getEncoder();
 466         Base64.Decoder decoder = Base64.getDecoder();
 467         //                src   pos, len  expected
 468         int[][] tests = { { 6,    3,   3,   3},   // xxx xxx    -> yyyy yyyy
 469                           { 6,    3,   4,   3},
 470                           { 6,    3,   5,   3},
 471                           { 6,    3,   6,   6},
 472                           { 6,   11,   4,   3},
 473                           { 6,   11,   4,   3},
 474                           { 6,   11,   5,   3},
 475                           { 6,   11,   6,   6},
 476                           { 7,    3,   6,   6},   // xxx xxx x  -> yyyy yyyy yy==
 477                           { 7,    3,   7,   7},
 478                           { 7,   11,   6,   6},
 479                           { 7,   11,   7,   7},
 480                           { 8,    3,   6,   6},   // xxx xxx xx -> yyyy yyyy yyy=
 481                           { 8,    3,   7,   6},
 482                           { 8,    3,   8,   8},
 483                           { 8,   13,   6,   6},
 484                           { 8,   13,   7,   6},
 485                           { 8,   13,   8,   8},
 486 
 487         };
 488         ByteBuffer dstBuf = ByteBuffer.allocate(100);
 489         for (boolean direct : new boolean[] { false, true}) {
 490             for (int[] test : tests) {
 491                 byte[] src = new byte[test[0]];
 492                 rnd.nextBytes(src);
 493                 ByteBuffer srcBuf = direct ? ByteBuffer.allocate(100)
 494                                            : ByteBuffer.allocateDirect(100);
 495                 srcBuf.put(encoder.encode(src)).flip();
 496                 dstBuf.clear().position(test[1]).limit(test[1]+ test[2]);
 497                 int ret = decoder.decode(srcBuf, dstBuf);
 498                 if (ret != test[3]) {
 499                     System.out.printf(" [%6s] src=%d, pos=%d, len=%d, expected=%d, ret=%d%n",
 500                                       direct?"direct":"",
 501                                       test[0], test[1], test[2], test[3], ret);
 502                     throw new RuntimeException("ret != expected");
 503                 }
 504             }
 505         }
 506     }
 507 
 508     private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected)
 509         throws Throwable {
 510 
 511         ByteBuffer bout = enc.encode(bin);
 512         byte[] buf = new byte[bout.remaining()];
 513         bout.get(buf);
 514         if (bin.hasRemaining()) {
 515             throw new RuntimeException(
 516                 "Base64 enc.encode(ByteBuffer) failed!");
 517         }
 518         checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
 519     }
 520 
 521     private static final void testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)
 522         throws Throwable {
 523 
 524         ByteBuffer bout = dec.decode(bin);
 525         byte[] buf = new byte[bout.remaining()];
 526         bout.get(buf);
 527         checkEqual(buf, expected, "Base64 dec.decode(bf) failed!");
 528     }
 529 
 530     private static final void testEncode(Base64.Encoder enc, byte[] expected,
 531                                          ByteBuffer ibb, ByteBuffer obb)
 532         throws Throwable {
 533         Random rnd = new Random();
 534         int bytesOut = enc.encode(ibb, obb, 0);
 535         if (ibb.hasRemaining()) {
 536             throw new RuntimeException(
 537                 "Base64 enc.encode(bf, bf) failed with wrong return!");
 538         }
 539         obb.flip();
 540         byte[] buf = new byte[obb.remaining()];
 541         obb.get(buf);
 542         checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
 543         ibb.rewind();
 544         obb.position(0);
 545         obb.limit(0);
 546         bytesOut = 0;
 547 
 548         do {  // increase the "limit" incrementally & randomly
 549             int n = rnd.nextInt(expected.length - obb.position());
 550             if (n == 0)
 551                 n = 1;
 552             obb.limit(obb.limit() + n);
 553             //obb.limit(Math.min(obb.limit() + n, expected.length));
 554             bytesOut = enc.encode(ibb, obb, bytesOut);
 555         } while (ibb.hasRemaining());
 556         obb.flip();
 557         buf = new byte[obb.remaining()];
 558         obb.get(buf);
 559         checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
 560     }
 561 
 562     private static final void testDecode(Base64.Decoder dec, byte[] expected,
 563                                          ByteBuffer ibb, ByteBuffer obb)
 564         throws Throwable {
 565         Random rnd = new Random();
 566 
 567         dec.decode(ibb, obb);
 568         if (ibb.hasRemaining()) {
 569             throw new RuntimeException(
 570                 "Base64 dec.decode(bf, bf) failed with un-decoded ibb!");
 571         }
 572         obb.flip();
 573         byte[] buf = new byte[obb.remaining()];
 574         obb.get(buf);
 575         checkEqual(buf, expected, "Base64 dec.decode(bf, bf) failed!");
 576 
 577         ibb.rewind();
 578         obb.position(0);
 579         obb.limit(0);
 580         do {  // increase the "limit" incrementally & randomly
 581             int n = rnd.nextInt(expected.length - obb.position());
 582             if (n == 0)
 583                 n = 1;
 584             obb.limit(obb.limit() + n);
 585             dec.decode(ibb, obb);
 586          } while (ibb.hasRemaining());
 587 
 588 
 589         obb.flip();
 590         buf = new byte[obb.remaining()];
 591         obb.get(buf);
 592         checkEqual(buf, expected, "Base64 dec.decode(bf, bf) failed!");
 593     }
 594 
 595     private static final void checkEqual(int v1, int v2, String msg)
 596         throws Throwable {
 597        if (v1 != v2) {
 598            System.out.printf("    v1=%d%n", v1);
 599            System.out.printf("    v2=%d%n", v2);
 600            throw new RuntimeException(msg);
 601        }
 602     }
 603 
 604     private static final void checkEqual(byte[] r1, byte[] r2, String msg)
 605         throws Throwable {
 606        if (!Arrays.equals(r1, r2)) {
 607            System.out.printf("    r1[%d]=[%s]%n", r1.length, new String(r1));
 608            System.out.printf("    r2[%d]=[%s]%n", r2.length, new String(r2));
 609            throw new RuntimeException(msg);
 610        }
 611     }
 612 
 613     // remove line feeds,
 614     private static final byte[] normalize(byte[] src) {
 615         int n = 0;
 616         boolean hasUrl = false;
 617         for (int i = 0; i < src.length; i++) {
 618             if (src[i] == '\r' || src[i] == '\n')
 619                 n++;
 620             if (src[i] == '-' || src[i] == '_')
 621                 hasUrl = true;
 622         }
 623         if (n == 0 && hasUrl == false)
 624             return src;
 625         byte[] ret = new byte[src.length - n];
 626         int j = 0;
 627         for (int i = 0; i < src.length; i++) {
 628             if (src[i] == '-')
 629                 ret[j++] = '+';
 630             else if (src[i] == '_')
 631                 ret[j++] = '/';
 632             else if (src[i] != '\r' && src[i] != '\n')
 633                 ret[j++] = src[i];
 634         }
 635         return ret;
 636     }
 637 }