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