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