blob: 6b37772d7f623da3e60cfa7741afbe60957b526d [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/**
sherman315907d2012-12-01 11:36:25 -080025 * @test 4235519 8004212
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();
sherman313292b2012-11-27 22:07:11 -0800112 }
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 }
299
300 private static void testNull(final Base64.Decoder dec) {
301 checkNull(new Runnable() { public void run() { dec.decode(ba_null); }});
302 checkNull(new Runnable() { public void run() { dec.decode(str_null); }});
303 checkNull(new Runnable() { public void run() { dec.decode(ba_null, new byte[10]); }});
304 checkNull(new Runnable() { public void run() { dec.decode(new byte[10], ba_null); }});
305 checkNull(new Runnable() { public void run() { dec.decode(bb_null); }});
306 checkNull(new Runnable() { public void run() { dec.decode(bb_null, ByteBuffer.allocate(10)); }});
307 checkNull(new Runnable() { public void run() { dec.decode(ByteBuffer.allocate(10), bb_null); }});
308 }
309
310 private static interface Testable {
311 public void test() throws Throwable;
312 }
313
314 private static void testIOE(final Base64.Encoder enc) throws Throwable {
315 ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
316 final OutputStream os = enc.wrap(baos);
317 os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});
318 os.close();
319 checkIOE(new Testable() { public void test() throws Throwable { os.write(10); }});
320 checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}); }});
321 checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}, 1, 4); }});
322 }
323
324 private static void testIOE(final Base64.Decoder dec, byte[] decoded) throws Throwable {
325 ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
326 final InputStream is = dec.wrap(bais);
327 is.read(new byte[10]);
328 is.close();
329 checkIOE(new Testable() { public void test() throws Throwable { is.read(); }});
330 checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}); }});
331 checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}, 1, 4); }});
332 checkIOE(new Testable() { public void test() throws Throwable { is.available(); }});
333 checkIOE(new Testable() { public void test() throws Throwable { is.skip(20); }});
334 }
335
336 private static final void checkNull(Runnable r) {
337 try {
338 r.run();
339 throw new RuntimeException("NPE is not thrown as expected");
340 } catch (NullPointerException npe) {}
341 }
342
343 private static final void checkIOE(Testable t) throws Throwable {
344 try {
345 t.test();
346 throw new RuntimeException("IOE is not thrown as expected");
347 } catch (IOException ioe) {}
348 }
349
350 private static final void checkIAE(Runnable r) throws Throwable {
351 try {
352 r.run();
353 throw new RuntimeException("IAE is not thrown as expected");
354 } catch (IllegalArgumentException iae) {}
355 }
356
sherman315907d2012-12-01 11:36:25 -0800357
358 private static void testDecBufRet() throws Throwable {
359 Random rnd = new java.util.Random();
360 Base64.Encoder encoder = Base64.getEncoder();
361 Base64.Decoder decoder = Base64.getDecoder();
362 // src pos, len expected
363 int[][] tests = { { 6, 3, 3, 3}, // xxx xxx -> yyyy yyyy
364 { 6, 3, 4, 3},
365 { 6, 3, 5, 3},
366 { 6, 3, 6, 6},
367 { 6, 11, 4, 3},
368 { 6, 11, 4, 3},
369 { 6, 11, 5, 3},
370 { 6, 11, 6, 6},
371 { 7, 3, 6, 6}, // xxx xxx x -> yyyy yyyy yy==
372 { 7, 3, 7, 7},
373 { 7, 11, 6, 6},
374 { 7, 11, 7, 7},
375 { 8, 3, 6, 6}, // xxx xxx xx -> yyyy yyyy yyy=
376 { 8, 3, 7, 6},
377 { 8, 3, 8, 8},
378 { 8, 13, 6, 6},
379 { 8, 13, 7, 6},
380 { 8, 13, 8, 8},
381
382 };
383 ByteBuffer dstBuf = ByteBuffer.allocate(100);
384 for (boolean direct : new boolean[] { false, true}) {
385 for (int[] test : tests) {
386 byte[] src = new byte[test[0]];
387 rnd.nextBytes(src);
388 ByteBuffer srcBuf = direct ? ByteBuffer.allocate(100)
389 : ByteBuffer.allocateDirect(100);
390 srcBuf.put(encoder.encode(src)).flip();
391 dstBuf.clear().position(test[1]).limit(test[1]+ test[2]);
392 int ret = decoder.decode(srcBuf, dstBuf);
393 if (ret != test[3]) {
394 System.out.printf(" [%6s] src=%d, pos=%d, len=%d, expected=%d, ret=%d%n",
395 direct?"direct":"",
396 test[0], test[1], test[2], test[3], ret);
397 throw new RuntimeException("ret != expected");
398 }
399 }
400 }
401 }
402
sherman313292b2012-11-27 22:07:11 -0800403 private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected)
404 throws Throwable {
405
406 ByteBuffer bout = enc.encode(bin);
407 byte[] buf = new byte[bout.remaining()];
408 bout.get(buf);
409 if (bin.hasRemaining()) {
410 throw new RuntimeException(
411 "Base64 enc.encode(ByteBuffer) failed!");
412 }
413 checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
414 }
415
416 private static final void testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)
417 throws Throwable {
418
419 ByteBuffer bout = dec.decode(bin);
420 byte[] buf = new byte[bout.remaining()];
421 bout.get(buf);
422 checkEqual(buf, expected, "Base64 dec.decode(bf) failed!");
423 }
424
425 private static final void testEncode(Base64.Encoder enc, byte[] expected,
426 ByteBuffer ibb, ByteBuffer obb)
427 throws Throwable {
428 Random rnd = new Random();
429 int bytesOut = enc.encode(ibb, obb, 0);
430 if (ibb.hasRemaining()) {
431 throw new RuntimeException(
432 "Base64 enc.encode(bf, bf) failed with wrong return!");
433 }
434 obb.flip();
435 byte[] buf = new byte[obb.remaining()];
436 obb.get(buf);
437 checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
438 ibb.rewind();
439 obb.position(0);
440 obb.limit(0);
441 bytesOut = 0;
442
443 do { // increase the "limit" incrementally & randomly
444 int n = rnd.nextInt(expected.length - obb.position());
445 if (n == 0)
446 n = 1;
447 obb.limit(obb.limit() + n);
448 //obb.limit(Math.min(obb.limit() + n, expected.length));
449 bytesOut = enc.encode(ibb, obb, bytesOut);
450 } while (ibb.hasRemaining());
451 obb.flip();
452 buf = new byte[obb.remaining()];
453 obb.get(buf);
454 checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
455 }
456
457 private static final void testDecode(Base64.Decoder dec, byte[] expected,
458 ByteBuffer ibb, ByteBuffer obb)
459 throws Throwable {
460 Random rnd = new Random();
461
462 dec.decode(ibb, obb);
463 if (ibb.hasRemaining()) {
464 throw new RuntimeException(
465 "Base64 dec.decode(bf, bf) failed with un-decoded ibb!");
466 }
467 obb.flip();
468 byte[] buf = new byte[obb.remaining()];
469 obb.get(buf);
470 checkEqual(buf, expected, "Base64 dec.decode(bf, bf) failed!");
471
472 ibb.rewind();
473 obb.position(0);
474 obb.limit(0);
475 do { // increase the "limit" incrementally & randomly
476 int n = rnd.nextInt(expected.length - obb.position());
477 if (n == 0)
478 n = 1;
479 obb.limit(obb.limit() + n);
480 dec.decode(ibb, obb);
481 } while (ibb.hasRemaining());
482
483
484 obb.flip();
485 buf = new byte[obb.remaining()];
486 obb.get(buf);
487 checkEqual(buf, expected, "Base64 dec.decode(bf, bf) failed!");
488 }
489
490 private static final void checkEqual(int v1, int v2, String msg)
491 throws Throwable {
492 if (v1 != v2) {
493 System.out.printf(" v1=%d%n", v1);
494 System.out.printf(" v2=%d%n", v2);
495 throw new RuntimeException(msg);
496 }
497 }
498
499 private static final void checkEqual(byte[] r1, byte[] r2, String msg)
500 throws Throwable {
501 if (!Arrays.equals(r1, r2)) {
502 System.out.printf(" r1[%d]=[%s]%n", r1.length, new String(r1));
503 System.out.printf(" r2[%d]=[%s]%n", r2.length, new String(r2));
504 throw new RuntimeException(msg);
505 }
506 }
507
508 // remove line feeds,
509 private static final byte[] normalize(byte[] src) {
510 int n = 0;
511 boolean hasUrl = false;
512 for (int i = 0; i < src.length; i++) {
513 if (src[i] == '\r' || src[i] == '\n')
514 n++;
515 if (src[i] == '-' || src[i] == '_')
516 hasUrl = true;
517 }
518 if (n == 0 && hasUrl == false)
519 return src;
520 byte[] ret = new byte[src.length - n];
521 int j = 0;
522 for (int i = 0; i < src.length; i++) {
523 if (src[i] == '-')
524 ret[j++] = '+';
525 else if (src[i] == '_')
526 ret[j++] = '/';
527 else if (src[i] != '\r' && src[i] != '\n')
528 ret[j++] = src[i];
529 }
530 return ret;
531 }
532}