1 /*
2  * Copyright (c) 2012, 2017, 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
26  * @bug 4235519 8004212 8005394 8007298 8006295 8006315 8006530 8007379 8008925
27  *      8014217 8025003 8026330 8028397 8129544 8165243 8176379
28  * @summary tests java.util.Base64
29  * @library /test/lib
30  * @build jdk.test.lib.RandomFactory
31  * @run main TestBase64
32  * @key randomness
33  */
34 
35 package test.java.util.Base64;
36 
37 import android.platform.test.annotations.LargeTest;
38 
39 import java.io.ByteArrayInputStream;
40 import java.io.ByteArrayOutputStream;
41 import java.io.InputStream;
42 import java.io.IOException;
43 import java.io.OutputStream;
44 import java.nio.ByteBuffer;
45 import java.util.Arrays;
46 import java.util.ArrayList;
47 import java.util.Base64;
48 import java.util.List;
49 import java.util.Random;
50 
51 import jdk.test.lib.RandomFactory;
52 
53 public class TestBase64 {
54 
55     private static final Random rnd = RandomFactory.getRandom();
56 
57     @LargeTest
main(String args[])58     public static void main(String args[]) throws Throwable {
59         int numRuns  = 10;
60         int numBytes = 200;
61         if (args.length > 1) {
62             numRuns  = Integer.parseInt(args[0]);
63             numBytes = Integer.parseInt(args[1]);
64         }
65 
66         test(Base64.getEncoder(), Base64.getDecoder(), numRuns, numBytes);
67         test(Base64.getUrlEncoder(), Base64.getUrlDecoder(), numRuns, numBytes);
68         test(Base64.getMimeEncoder(), Base64.getMimeDecoder(), numRuns, numBytes);
69 
70         byte[] nl_1 = new byte[] {'\n'};
71         byte[] nl_2 = new byte[] {'\n', '\r'};
72         byte[] nl_3 = new byte[] {'\n', '\r', '\n'};
73         for (int i = 0; i < 10; i++) {
74             int len = rnd.nextInt(200) + 4;
75             test(Base64.getMimeEncoder(len, nl_1),
76                  Base64.getMimeDecoder(),
77                  numRuns, numBytes);
78             test(Base64.getMimeEncoder(len, nl_2),
79                  Base64.getMimeDecoder(),
80                  numRuns, numBytes);
81             test(Base64.getMimeEncoder(len, nl_3),
82                  Base64.getMimeDecoder(),
83                  numRuns, numBytes);
84         }
85 
86         // test mime case with < 4 length
87         for (int len = 0; len < 4; len++) {
88             test(Base64.getMimeEncoder(len, nl_1),
89                  Base64.getMimeDecoder(),
90                  numRuns, numBytes);
91 
92             test(Base64.getMimeEncoder(len, nl_2),
93                  Base64.getMimeDecoder(),
94                  numRuns, numBytes);
95 
96             test(Base64.getMimeEncoder(len, nl_3),
97                  Base64.getMimeDecoder(),
98                  numRuns, numBytes);
99         }
100 
101         testNull(Base64.getEncoder());
102         testNull(Base64.getUrlEncoder());
103         testNull(Base64.getMimeEncoder());
104         testNull(Base64.getMimeEncoder(10, new byte[]{'\n'}));
105         testNull(Base64.getDecoder());
106         testNull(Base64.getUrlDecoder());
107         testNull(Base64.getMimeDecoder());
108         checkNull(() -> Base64.getMimeEncoder(10, null));
109 
110         testIOE(Base64.getEncoder());
111         testIOE(Base64.getUrlEncoder());
112         testIOE(Base64.getMimeEncoder());
113         testIOE(Base64.getMimeEncoder(10, new byte[]{'\n'}));
114 
115         byte[] src = new byte[1024];
116         rnd.nextBytes(src);
117         final byte[] decoded = Base64.getEncoder().encode(src);
118         testIOE(Base64.getDecoder(), decoded);
119         testIOE(Base64.getMimeDecoder(), decoded);
120         testIOE(Base64.getUrlDecoder(), Base64.getUrlEncoder().encode(src));
121 
122         // illegal line separator
123         checkIAE(() -> Base64.getMimeEncoder(10, new byte[]{'\r', 'N'}));
124 
125         // malformed padding/ending
126         testMalformedPadding();
127 
128         // illegal base64 character
129         decoded[2] = (byte)0xe0;
130         checkIAE(() -> Base64.getDecoder().decode(decoded));
131         checkIAE(() -> Base64.getDecoder().decode(decoded, new byte[1024]));
132         checkIAE(() -> Base64.getDecoder().decode(ByteBuffer.wrap(decoded)));
133 
134         // test single-non-base64 character for mime decoding
135         testSingleNonBase64MimeDec();
136 
137         // test decoding of unpadded data
138         testDecodeUnpadded();
139 
140         // test mime decoding with ignored character after padding
141         testDecodeIgnoredAfterPadding();
142 
143         // given invalid args, encoder should not produce output
144         testEncoderKeepsSilence(Base64.getEncoder());
145         testEncoderKeepsSilence(Base64.getUrlEncoder());
146         testEncoderKeepsSilence(Base64.getMimeEncoder());
147 
148         // given invalid args, decoder should not consume input
149         testDecoderKeepsAbstinence(Base64.getDecoder());
150         testDecoderKeepsAbstinence(Base64.getUrlDecoder());
151         testDecoderKeepsAbstinence(Base64.getMimeDecoder());
152     }
153 
test(Base64.Encoder enc, Base64.Decoder dec, int numRuns, int numBytes)154     private static void test(Base64.Encoder enc, Base64.Decoder dec,
155                              int numRuns, int numBytes) throws Throwable {
156         enc.encode(new byte[0]);
157         dec.decode(new byte[0]);
158 
159         for (boolean withoutPadding : new boolean[] { false, true}) {
160             if (withoutPadding) {
161                  enc = enc.withoutPadding();
162             }
163             for (int i=0; i<numRuns; i++) {
164                 for (int j=1; j<numBytes; j++) {
165                     byte[] orig = new byte[j];
166                     rnd.nextBytes(orig);
167 
168                     // --------testing encode/decode(byte[])--------
169                     byte[] encoded = enc.encode(orig);
170                     byte[] decoded = dec.decode(encoded);
171 
172                     checkEqual(orig, decoded,
173                                "Base64 array encoding/decoding failed!");
174                     if (withoutPadding) {
175                         if (encoded[encoded.length - 1] == '=')
176                             throw new RuntimeException(
177                                "Base64 enc.encode().withoutPadding() has padding!");
178                     }
179                     // --------testing encodetoString(byte[])/decode(String)--------
180                     String str = enc.encodeToString(orig);
181                     if (!Arrays.equals(str.getBytes("ASCII"), encoded)) {
182                         throw new RuntimeException(
183                             "Base64 encodingToString() failed!");
184                     }
185                     byte[] buf = dec.decode(new String(encoded, "ASCII"));
186                     checkEqual(buf, orig, "Base64 decoding(String) failed!");
187 
188                     //-------- testing encode/decode(Buffer)--------
189                     testEncode(enc, ByteBuffer.wrap(orig), encoded);
190                     ByteBuffer bin = ByteBuffer.allocateDirect(orig.length);
191                     bin.put(orig).flip();
192                     testEncode(enc, bin, encoded);
193 
194                     testDecode(dec, ByteBuffer.wrap(encoded), orig);
195                     bin = ByteBuffer.allocateDirect(encoded.length);
196                     bin.put(encoded).flip();
197                     testDecode(dec, bin, orig);
198 
199                     // --------testing decode.wrap(input stream)--------
200                     // 1) random buf length
201                     ByteArrayInputStream bais = new ByteArrayInputStream(encoded);
202                     InputStream is = dec.wrap(bais);
203                     buf = new byte[orig.length + 10];
204                     int len = orig.length;
205                     int off = 0;
206                     while (true) {
207                         int n = rnd.nextInt(len);
208                         if (n == 0)
209                             n = 1;
210                         n = is.read(buf, off, n);
211                         if (n == -1) {
212                             checkEqual(off, orig.length,
213                                        "Base64 stream decoding failed");
214                             break;
215                         }
216                         off += n;
217                         len -= n;
218                         if (len == 0)
219                             break;
220                     }
221                     buf = Arrays.copyOf(buf, off);
222                     checkEqual(buf, orig, "Base64 stream decoding failed!");
223 
224                     // 2) read one byte each
225                     bais.reset();
226                     is = dec.wrap(bais);
227                     buf = new byte[orig.length + 10];
228                     off = 0;
229                     int b;
230                     while ((b = is.read()) != -1) {
231                         buf[off++] = (byte)b;
232                     }
233                     buf = Arrays.copyOf(buf, off);
234                     checkEqual(buf, orig, "Base64 stream decoding failed!");
235 
236                     // --------testing encode.wrap(output stream)--------
237                     ByteArrayOutputStream baos = new ByteArrayOutputStream((orig.length + 2) / 3 * 4 + 10);
238                     OutputStream os = enc.wrap(baos);
239                     off = 0;
240                     len = orig.length;
241                     for (int k = 0; k < 5; k++) {
242                         if (len == 0)
243                             break;
244                         int n = rnd.nextInt(len);
245                         if (n == 0)
246                             n = 1;
247                         os.write(orig, off, n);
248                         off += n;
249                         len -= n;
250                     }
251                     if (len != 0)
252                         os.write(orig, off, len);
253                     os.close();
254                     buf = baos.toByteArray();
255                     checkEqual(buf, encoded, "Base64 stream encoding failed!");
256 
257                     // 2) write one byte each
258                     baos.reset();
259                     os = enc.wrap(baos);
260                     off = 0;
261                     while (off < orig.length) {
262                         os.write(orig[off++]);
263                     }
264                     os.close();
265                     buf = baos.toByteArray();
266                     checkEqual(buf, encoded, "Base64 stream encoding failed!");
267 
268                     // --------testing encode(in, out); -> bigger buf--------
269                     buf = new byte[encoded.length + rnd.nextInt(100)];
270                     int ret = enc.encode(orig, buf);
271                     checkEqual(ret, encoded.length,
272                                "Base64 enc.encode(src, null) returns wrong size!");
273                     buf = Arrays.copyOf(buf, ret);
274                     checkEqual(buf, encoded,
275                                "Base64 enc.encode(src, dst) failed!");
276 
277                     // --------testing decode(in, out); -> bigger buf--------
278                     buf = new byte[orig.length + rnd.nextInt(100)];
279                     ret = dec.decode(encoded, buf);
280                     checkEqual(ret, orig.length,
281                               "Base64 enc.encode(src, null) returns wrong size!");
282                     buf = Arrays.copyOf(buf, ret);
283                     checkEqual(buf, orig,
284                                "Base64 dec.decode(src, dst) failed!");
285 
286                 }
287             }
288         }
289     }
290 
291     private static final byte[] ba_null = null;
292     private static final String str_null = null;
293     private static final ByteBuffer bb_null = null;
294 
testNull(Base64.Encoder enc)295     private static void testNull(Base64.Encoder enc) {
296         checkNull(() -> enc.encode(ba_null));
297         checkNull(() -> enc.encodeToString(ba_null));
298         checkNull(() -> enc.encode(ba_null, new byte[10]));
299         checkNull(() -> enc.encode(new byte[10], ba_null));
300         checkNull(() -> enc.encode(bb_null));
301         checkNull(() -> enc.wrap((OutputStream)null));
302     }
303 
testNull(Base64.Decoder dec)304     private static void testNull(Base64.Decoder dec) {
305         checkNull(() -> dec.decode(ba_null));
306         checkNull(() -> dec.decode(str_null));
307         checkNull(() -> dec.decode(ba_null, new byte[10]));
308         checkNull(() -> dec.decode(new byte[10], ba_null));
309         checkNull(() -> dec.decode(bb_null));
310         checkNull(() -> dec.wrap((InputStream)null));
311     }
312 
313     @FunctionalInterface
314     private static interface Testable {
test()315         public void test() throws Throwable;
316     }
317 
testIOE(Base64.Encoder enc)318     private static void testIOE(Base64.Encoder enc) throws Throwable {
319         ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
320         OutputStream os = enc.wrap(baos);
321         os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});
322         os.close();
323         checkIOE(() -> os.write(10));
324         checkIOE(() -> os.write(new byte[] {10}));
325         checkIOE(() -> os.write(new byte[] {10}, 1, 4));
326     }
327 
testIOE(Base64.Decoder dec, byte[] decoded)328     private static void testIOE(Base64.Decoder dec, byte[] decoded) throws Throwable {
329         ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
330         InputStream is = dec.wrap(bais);
331         is.read(new byte[10]);
332         is.close();
333         checkIOE(() -> is.read());
334         checkIOE(() -> is.read(new byte[] {10}));
335         checkIOE(() -> is.read(new byte[] {10}, 1, 4));
336         checkIOE(() -> is.available());
337         checkIOE(() -> is.skip(20));
338     }
339 
checkNull(Runnable r)340     private static final void checkNull(Runnable r) {
341         try {
342             r.run();
343             throw new RuntimeException("NPE is not thrown as expected");
344         } catch (NullPointerException npe) {}
345     }
346 
checkIOE(Testable t)347     private static final void checkIOE(Testable t) throws Throwable {
348         try {
349             t.test();
350             throw new RuntimeException("IOE is not thrown as expected");
351         } catch (IOException ioe) {}
352     }
353 
checkIAE(Runnable r)354     private static final void checkIAE(Runnable r) throws Throwable {
355         try {
356             r.run();
357             throw new RuntimeException("IAE is not thrown as expected");
358         } catch (IllegalArgumentException iae) {}
359     }
360 
testDecodeIgnoredAfterPadding()361     private static void testDecodeIgnoredAfterPadding() throws Throwable {
362         for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {
363             byte[][] src = new byte[][] {
364                 "A".getBytes("ascii"),
365                 "AB".getBytes("ascii"),
366                 "ABC".getBytes("ascii"),
367                 "ABCD".getBytes("ascii"),
368                 "ABCDE".getBytes("ascii")
369             };
370             Base64.Encoder encM = Base64.getMimeEncoder();
371             Base64.Decoder decM = Base64.getMimeDecoder();
372             Base64.Encoder enc = Base64.getEncoder();
373             Base64.Decoder dec = Base64.getDecoder();
374             for (int i = 0; i < src.length; i++) {
375                 // decode(byte[])
376                 byte[] encoded = encM.encode(src[i]);
377                 encoded = Arrays.copyOf(encoded, encoded.length + 1);
378                 encoded[encoded.length - 1] = nonBase64;
379                 checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");
380                 byte[] decoded = new byte[src[i].length];
381                 decM.decode(encoded, decoded);
382                 checkEqual(decoded, src[i], "Non-base64 char is not ignored");
383 
384                 try {
385                     dec.decode(encoded);
386                     throw new RuntimeException("No IAE for non-base64 char");
387                 } catch (IllegalArgumentException iae) {}
388             }
389         }
390     }
391 
testMalformedPadding()392     private static void testMalformedPadding() throws Throwable {
393         Object[] data = new Object[] {
394             "$=#",       "",      0,      // illegal ending unit
395             "A",         "",      0,      // dangling single byte
396             "A=",        "",      0,
397             "A==",       "",      0,
398             "QUJDA",     "ABC",   4,
399             "QUJDA=",    "ABC",   4,
400             "QUJDA==",   "ABC",   4,
401 
402             "=",         "",      0,      // unnecessary padding
403             "QUJD=",     "ABC",   4,      //"ABC".encode() -> "QUJD"
404 
405             "AA=",       "",      0,      // incomplete padding
406             "QQ=",       "",      0,
407             "QQ=N",      "",      0,      // incorrect padding
408             "QQ=?",      "",      0,
409             "QUJDQQ=",   "ABC",   4,
410             "QUJDQQ=N",  "ABC",   4,
411             "QUJDQQ=?",  "ABC",   4,
412         };
413 
414         Base64.Decoder[] decs = new Base64.Decoder[] {
415             Base64.getDecoder(),
416             Base64.getUrlDecoder(),
417             Base64.getMimeDecoder()
418         };
419 
420         for (Base64.Decoder dec : decs) {
421             for (int i = 0; i < data.length; i += 3) {
422                 final String srcStr = (String)data[i];
423                 final byte[] srcBytes = srcStr.getBytes("ASCII");
424                 final ByteBuffer srcBB = ByteBuffer.wrap(srcBytes);
425                 byte[] expected = ((String)data[i + 1]).getBytes("ASCII");
426                 int pos = (Integer)data[i + 2];
427 
428                 // decode(byte[])
429                 checkIAE(() -> dec.decode(srcBytes));
430 
431                 // decode(String)
432                 checkIAE(() -> dec.decode(srcStr));
433 
434                 // decode(ByteBuffer)
435                 checkIAE(() -> dec.decode(srcBB));
436 
437                 // wrap stream
438                 checkIOE(new Testable() {
439                     public void test() throws IOException {
440                         try (InputStream is = dec.wrap(new ByteArrayInputStream(srcBytes))) {
441                             while (is.read() != -1);
442                         }
443                 }});
444             }
445         }
446 
447         // anything left after padding is "invalid"/IAE, if
448         // not MIME. In case of MIME, non-base64 character(s)
449         // is ignored.
450         checkIAE(() -> Base64.getDecoder().decode("AA==\u00D2"));
451         checkIAE(() -> Base64.getUrlDecoder().decode("AA==\u00D2"));
452         Base64.getMimeDecoder().decode("AA==\u00D2");
453      }
454 
testDecodeUnpadded()455     private static void  testDecodeUnpadded() throws Throwable {
456         byte[] srcA = new byte[] { 'Q', 'Q' };
457         byte[] srcAA = new byte[] { 'Q', 'Q', 'E'};
458         Base64.Decoder dec = Base64.getDecoder();
459         byte[] ret = dec.decode(srcA);
460         if (ret[0] != 'A')
461             throw new RuntimeException("Decoding unpadding input A failed");
462         ret = dec.decode(srcAA);
463         if (ret[0] != 'A' && ret[1] != 'A')
464             throw new RuntimeException("Decoding unpadding input AA failed");
465         ret = new byte[10];
466         if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 1 &&
467             ret[0] != 'A')
468             throw new RuntimeException("Decoding unpadding input A from stream failed");
469         if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 2 &&
470             ret[0] != 'A' && ret[1] != 'A')
471             throw new RuntimeException("Decoding unpadding input AA from stream failed");
472     }
473 
474     // single-non-base64-char should be ignored for mime decoding, but
475     // iae for basic decoding
testSingleNonBase64MimeDec()476     private static void testSingleNonBase64MimeDec() throws Throwable {
477         for (String nonBase64 : new String[] {"#", "(", "!", "\\", "-", "_"}) {
478             if (Base64.getMimeDecoder().decode(nonBase64).length != 0) {
479                 throw new RuntimeException("non-base64 char is not ignored");
480             }
481             try {
482                 Base64.getDecoder().decode(nonBase64);
483                 throw new RuntimeException("No IAE for single non-base64 char");
484             } catch (IllegalArgumentException iae) {}
485         }
486     }
487 
testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected)488     private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected)
489         throws Throwable {
490 
491         ByteBuffer bout = enc.encode(bin);
492         byte[] buf = new byte[bout.remaining()];
493         bout.get(buf);
494         if (bin.hasRemaining()) {
495             throw new RuntimeException(
496                 "Base64 enc.encode(ByteBuffer) failed!");
497         }
498         checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
499     }
500 
testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)501     private static final void testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)
502         throws Throwable {
503 
504         ByteBuffer bout = dec.decode(bin);
505         byte[] buf = new byte[bout.remaining()];
506         bout.get(buf);
507         checkEqual(buf, expected, "Base64 dec.decode(bf) failed!");
508     }
509 
checkEqual(int v1, int v2, String msg)510     private static final void checkEqual(int v1, int v2, String msg)
511         throws Throwable {
512        if (v1 != v2) {
513            System.out.printf("    v1=%d%n", v1);
514            System.out.printf("    v2=%d%n", v2);
515            throw new RuntimeException(msg);
516        }
517     }
518 
checkEqual(byte[] r1, byte[] r2, String msg)519     private static final void checkEqual(byte[] r1, byte[] r2, String msg)
520         throws Throwable {
521        if (!Arrays.equals(r1, r2)) {
522            System.out.printf("    r1[%d]=[%s]%n", r1.length, new String(r1));
523            System.out.printf("    r2[%d]=[%s]%n", r2.length, new String(r2));
524            throw new RuntimeException(msg);
525        }
526     }
527 
528     // remove line feeds,
normalize(byte[] src)529     private static final byte[] normalize(byte[] src) {
530         int n = 0;
531         boolean hasUrl = false;
532         for (int i = 0; i < src.length; i++) {
533             if (src[i] == '\r' || src[i] == '\n')
534                 n++;
535             if (src[i] == '-' || src[i] == '_')
536                 hasUrl = true;
537         }
538         if (n == 0 && hasUrl == false)
539             return src;
540         byte[] ret = new byte[src.length - n];
541         int j = 0;
542         for (int i = 0; i < src.length; i++) {
543             if (src[i] == '-')
544                 ret[j++] = '+';
545             else if (src[i] == '_')
546                 ret[j++] = '/';
547             else if (src[i] != '\r' && src[i] != '\n')
548                 ret[j++] = src[i];
549         }
550         return ret;
551     }
552 
testEncoderKeepsSilence(Base64.Encoder enc)553     private static void testEncoderKeepsSilence(Base64.Encoder enc)
554             throws Throwable {
555         List<Integer> vals = new ArrayList<>(List.of(Integer.MIN_VALUE,
556                 Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
557                 Integer.MAX_VALUE - 1, Integer.MAX_VALUE));
558         vals.addAll(List.of(rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
559                 rnd.nextInt()));
560         byte[] buf = new byte[] {1, 0, 91};
561         for (int off : vals) {
562             for (int len : vals) {
563                 if (off >= 0 && len >= 0 && off <= buf.length - len) {
564                     // valid args, skip them
565                     continue;
566                 }
567                 // invalid args, test them
568                 System.out.println("testing off=" + off + ", len=" + len);
569 
570                 ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
571                 try (OutputStream os = enc.wrap(baos)) {
572                     os.write(buf, off, len);
573                     throw new RuntimeException("Expected IOOBEx was not thrown");
574                 } catch (IndexOutOfBoundsException expected) {
575                 }
576                 if (baos.size() > 0)
577                     throw new RuntimeException("No output was expected, but got "
578                             + baos.size() + " bytes");
579             }
580         }
581     }
582 
testDecoderKeepsAbstinence(Base64.Decoder dec)583     private static void testDecoderKeepsAbstinence(Base64.Decoder dec)
584             throws Throwable {
585         List<Integer> vals = new ArrayList<>(List.of(Integer.MIN_VALUE,
586                 Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
587                 Integer.MAX_VALUE - 1, Integer.MAX_VALUE));
588         vals.addAll(List.of(rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
589                 rnd.nextInt()));
590         byte[] buf = new byte[3];
591         for (int off : vals) {
592             for (int len : vals) {
593                 if (off >= 0 && len >= 0 && off <= buf.length - len) {
594                     // valid args, skip them
595                     continue;
596                 }
597                 // invalid args, test them
598                 System.out.println("testing off=" + off + ", len=" + len);
599 
600                 String input = "AAAAAAAAAAAAAAAAAAAAAA";
601                 ByteArrayInputStream bais =
602                         new ByteArrayInputStream(input.getBytes("Latin1"));
603                 try (InputStream is = dec.wrap(bais)) {
604                     is.read(buf, off, len);
605                     throw new RuntimeException("Expected IOOBEx was not thrown");
606                 } catch (IndexOutOfBoundsException expected) {
607                 }
608                 if (bais.available() != input.length())
609                     throw new RuntimeException("No input should be consumed, "
610                             + "but consumed " + (input.length() - bais.available())
611                             + " bytes");
612             }
613         }
614     }
615 }
616