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