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