Path: blob/master/test/jdk/java/util/Base64/TestBase64.java
41149 views
/*1* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 4235519 8004212 8005394 8007298 8006295 8006315 8006530 8007379 800892526* 8014217 8025003 8026330 8028397 8129544 8165243 8176379 822218727* @summary tests java.util.Base6428* @library /test/lib29* @build jdk.test.lib.RandomFactory30* @run main TestBase6431* @key randomness32*/3334import java.io.ByteArrayInputStream;35import java.io.ByteArrayOutputStream;36import java.io.InputStream;37import java.io.IOException;38import java.io.OutputStream;39import java.nio.ByteBuffer;40import java.util.Arrays;41import java.util.ArrayList;42import java.util.Base64;43import java.util.List;44import java.util.Random;4546import jdk.test.lib.RandomFactory;4748public class TestBase64 {4950private static final Random rnd = RandomFactory.getRandom();5152public static void main(String args[]) throws Throwable {53int numRuns = 10;54int numBytes = 200;55if (args.length > 1) {56numRuns = Integer.parseInt(args[0]);57numBytes = Integer.parseInt(args[1]);58}5960test(Base64.getEncoder(), Base64.getDecoder(), numRuns, numBytes);61test(Base64.getUrlEncoder(), Base64.getUrlDecoder(), numRuns, numBytes);62test(Base64.getMimeEncoder(), Base64.getMimeDecoder(), numRuns, numBytes);6364byte[] nl_1 = new byte[] {'\n'};65byte[] nl_2 = new byte[] {'\n', '\r'};66byte[] nl_3 = new byte[] {'\n', '\r', '\n'};67for (int i = 0; i < 10; i++) {68int len = rnd.nextInt(200) + 4;69test(Base64.getMimeEncoder(len, nl_1),70Base64.getMimeDecoder(),71numRuns, numBytes);72test(Base64.getMimeEncoder(len, nl_2),73Base64.getMimeDecoder(),74numRuns, numBytes);75test(Base64.getMimeEncoder(len, nl_3),76Base64.getMimeDecoder(),77numRuns, numBytes);78}7980// test mime case with < 4 length81for (int len = 0; len < 4; len++) {82test(Base64.getMimeEncoder(len, nl_1),83Base64.getMimeDecoder(),84numRuns, numBytes);8586test(Base64.getMimeEncoder(len, nl_2),87Base64.getMimeDecoder(),88numRuns, numBytes);8990test(Base64.getMimeEncoder(len, nl_3),91Base64.getMimeDecoder(),92numRuns, numBytes);93}9495testNull(Base64.getEncoder());96testNull(Base64.getUrlEncoder());97testNull(Base64.getMimeEncoder());98testNull(Base64.getMimeEncoder(10, new byte[]{'\n'}));99testNull(Base64.getDecoder());100testNull(Base64.getUrlDecoder());101testNull(Base64.getMimeDecoder());102checkNull(() -> Base64.getMimeEncoder(10, null));103104testIOE(Base64.getEncoder());105testIOE(Base64.getUrlEncoder());106testIOE(Base64.getMimeEncoder());107testIOE(Base64.getMimeEncoder(10, new byte[]{'\n'}));108109byte[] src = new byte[1024];110rnd.nextBytes(src);111final byte[] decoded = Base64.getEncoder().encode(src);112testIOE(Base64.getDecoder(), decoded);113testIOE(Base64.getMimeDecoder(), decoded);114testIOE(Base64.getUrlDecoder(), Base64.getUrlEncoder().encode(src));115116// illegal line separator117checkIAE(() -> Base64.getMimeEncoder(10, new byte[]{'\r', 'N'}));118119// malformed padding/ending120testMalformedPadding();121122// illegal base64 character123decoded[2] = (byte)0xe0;124checkIAE(() -> Base64.getDecoder().decode(decoded));125checkIAE(() -> Base64.getDecoder().decode(decoded, new byte[1024]));126checkIAE(() -> Base64.getDecoder().decode(ByteBuffer.wrap(decoded)));127128// test single-non-base64 character for mime decoding129testSingleNonBase64MimeDec();130131// test decoding of unpadded data132testDecodeUnpadded();133134// test mime decoding with ignored character after padding135testDecodeIgnoredAfterPadding();136137// given invalid args, encoder should not produce output138testEncoderKeepsSilence(Base64.getEncoder());139testEncoderKeepsSilence(Base64.getUrlEncoder());140testEncoderKeepsSilence(Base64.getMimeEncoder());141142// given invalid args, decoder should not consume input143testDecoderKeepsAbstinence(Base64.getDecoder());144testDecoderKeepsAbstinence(Base64.getUrlDecoder());145testDecoderKeepsAbstinence(Base64.getMimeDecoder());146147// tests patch addressing JDK-8222187148// https://bugs.openjdk.java.net/browse/JDK-8222187149testJDK_8222187();150}151152private static void test(Base64.Encoder enc, Base64.Decoder dec,153int numRuns, int numBytes) throws Throwable {154enc.encode(new byte[0]);155dec.decode(new byte[0]);156157for (boolean withoutPadding : new boolean[] { false, true}) {158if (withoutPadding) {159enc = enc.withoutPadding();160}161for (int i=0; i<numRuns; i++) {162for (int j=1; j<numBytes; j++) {163byte[] orig = new byte[j];164rnd.nextBytes(orig);165166// --------testing encode/decode(byte[])--------167byte[] encoded = enc.encode(orig);168byte[] decoded = dec.decode(encoded);169170checkEqual(orig, decoded,171"Base64 array encoding/decoding failed!");172if (withoutPadding) {173if (encoded[encoded.length - 1] == '=')174throw new RuntimeException(175"Base64 enc.encode().withoutPadding() has padding!");176}177// --------testing encodetoString(byte[])/decode(String)--------178String str = enc.encodeToString(orig);179if (!Arrays.equals(str.getBytes("ASCII"), encoded)) {180throw new RuntimeException(181"Base64 encodingToString() failed!");182}183byte[] buf = dec.decode(new String(encoded, "ASCII"));184checkEqual(buf, orig, "Base64 decoding(String) failed!");185186//-------- testing encode/decode(Buffer)--------187testEncode(enc, ByteBuffer.wrap(orig), encoded);188ByteBuffer bin = ByteBuffer.allocateDirect(orig.length);189bin.put(orig).flip();190testEncode(enc, bin, encoded);191192testDecode(dec, ByteBuffer.wrap(encoded), orig);193bin = ByteBuffer.allocateDirect(encoded.length);194bin.put(encoded).flip();195testDecode(dec, bin, orig);196197// --------testing decode.wrap(input stream)--------198// 1) random buf length199ByteArrayInputStream bais = new ByteArrayInputStream(encoded);200InputStream is = dec.wrap(bais);201buf = new byte[orig.length + 10];202int len = orig.length;203int off = 0;204while (true) {205int n = rnd.nextInt(len);206if (n == 0)207n = 1;208n = is.read(buf, off, n);209if (n == -1) {210checkEqual(off, orig.length,211"Base64 stream decoding failed");212break;213}214off += n;215len -= n;216if (len == 0)217break;218}219buf = Arrays.copyOf(buf, off);220checkEqual(buf, orig, "Base64 stream decoding failed!");221222// 2) read one byte each223bais.reset();224is = dec.wrap(bais);225buf = new byte[orig.length + 10];226off = 0;227int b;228while ((b = is.read()) != -1) {229buf[off++] = (byte)b;230}231buf = Arrays.copyOf(buf, off);232checkEqual(buf, orig, "Base64 stream decoding failed!");233234// --------testing encode.wrap(output stream)--------235ByteArrayOutputStream baos = new ByteArrayOutputStream((orig.length + 2) / 3 * 4 + 10);236OutputStream os = enc.wrap(baos);237off = 0;238len = orig.length;239for (int k = 0; k < 5; k++) {240if (len == 0)241break;242int n = rnd.nextInt(len);243if (n == 0)244n = 1;245os.write(orig, off, n);246off += n;247len -= n;248}249if (len != 0)250os.write(orig, off, len);251os.close();252buf = baos.toByteArray();253checkEqual(buf, encoded, "Base64 stream encoding failed!");254255// 2) write one byte each256baos.reset();257os = enc.wrap(baos);258off = 0;259while (off < orig.length) {260os.write(orig[off++]);261}262os.close();263buf = baos.toByteArray();264checkEqual(buf, encoded, "Base64 stream encoding failed!");265266// --------testing encode(in, out); -> bigger buf--------267buf = new byte[encoded.length + rnd.nextInt(100)];268int ret = enc.encode(orig, buf);269checkEqual(ret, encoded.length,270"Base64 enc.encode(src, null) returns wrong size!");271buf = Arrays.copyOf(buf, ret);272checkEqual(buf, encoded,273"Base64 enc.encode(src, dst) failed!");274275// --------testing decode(in, out); -> bigger buf--------276buf = new byte[orig.length + rnd.nextInt(100)];277ret = dec.decode(encoded, buf);278checkEqual(ret, orig.length,279"Base64 enc.encode(src, null) returns wrong size!");280buf = Arrays.copyOf(buf, ret);281checkEqual(buf, orig,282"Base64 dec.decode(src, dst) failed!");283284}285}286}287}288289private static final byte[] ba_null = null;290private static final String str_null = null;291private static final ByteBuffer bb_null = null;292293private static void testNull(Base64.Encoder enc) {294checkNull(() -> enc.encode(ba_null));295checkNull(() -> enc.encodeToString(ba_null));296checkNull(() -> enc.encode(ba_null, new byte[10]));297checkNull(() -> enc.encode(new byte[10], ba_null));298checkNull(() -> enc.encode(bb_null));299checkNull(() -> enc.wrap((OutputStream)null));300}301302private static void testNull(Base64.Decoder dec) {303checkNull(() -> dec.decode(ba_null));304checkNull(() -> dec.decode(str_null));305checkNull(() -> dec.decode(ba_null, new byte[10]));306checkNull(() -> dec.decode(new byte[10], ba_null));307checkNull(() -> dec.decode(bb_null));308checkNull(() -> dec.wrap((InputStream)null));309}310311@FunctionalInterface312private static interface Testable {313public void test() throws Throwable;314}315316private static void testIOE(Base64.Encoder enc) throws Throwable {317ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);318OutputStream os = enc.wrap(baos);319os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});320os.close();321checkIOE(() -> os.write(10));322checkIOE(() -> os.write(new byte[] {10}));323checkIOE(() -> os.write(new byte[] {10}, 1, 4));324}325326private static void testIOE(Base64.Decoder dec, byte[] decoded) throws Throwable {327ByteArrayInputStream bais = new ByteArrayInputStream(decoded);328InputStream is = dec.wrap(bais);329is.read(new byte[10]);330is.close();331checkIOE(() -> is.read());332checkIOE(() -> is.read(new byte[] {10}));333checkIOE(() -> is.read(new byte[] {10}, 1, 4));334checkIOE(() -> is.available());335checkIOE(() -> is.skip(20));336}337338private static final void checkNull(Runnable r) {339try {340r.run();341throw new RuntimeException("NPE is not thrown as expected");342} catch (NullPointerException npe) {}343}344345private static final void checkIOE(Testable t) throws Throwable {346try {347t.test();348throw new RuntimeException("IOE is not thrown as expected");349} catch (IOException ioe) {}350}351352private static final void checkIAE(Runnable r) throws Throwable {353try {354r.run();355throw new RuntimeException("IAE is not thrown as expected");356} catch (IllegalArgumentException iae) {}357}358359private static void testDecodeIgnoredAfterPadding() throws Throwable {360for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {361byte[][] src = new byte[][] {362"A".getBytes("ascii"),363"AB".getBytes("ascii"),364"ABC".getBytes("ascii"),365"ABCD".getBytes("ascii"),366"ABCDE".getBytes("ascii")367};368Base64.Encoder encM = Base64.getMimeEncoder();369Base64.Decoder decM = Base64.getMimeDecoder();370Base64.Encoder enc = Base64.getEncoder();371Base64.Decoder dec = Base64.getDecoder();372for (int i = 0; i < src.length; i++) {373// decode(byte[])374byte[] encoded = encM.encode(src[i]);375encoded = Arrays.copyOf(encoded, encoded.length + 1);376encoded[encoded.length - 1] = nonBase64;377checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");378byte[] decoded = new byte[src[i].length];379decM.decode(encoded, decoded);380checkEqual(decoded, src[i], "Non-base64 char is not ignored");381382try {383dec.decode(encoded);384throw new RuntimeException("No IAE for non-base64 char");385} catch (IllegalArgumentException iae) {}386}387}388}389390private static void testMalformedPadding() throws Throwable {391Object[] data = new Object[] {392"$=#", "", 0, // illegal ending unit393"A", "", 0, // dangling single byte394"A=", "", 0,395"A==", "", 0,396"QUJDA", "ABC", 4,397"QUJDA=", "ABC", 4,398"QUJDA==", "ABC", 4,399400"=", "", 0, // unnecessary padding401"QUJD=", "ABC", 4, //"ABC".encode() -> "QUJD"402403"AA=", "", 0, // incomplete padding404"QQ=", "", 0,405"QQ=N", "", 0, // incorrect padding406"QQ=?", "", 0,407"QUJDQQ=", "ABC", 4,408"QUJDQQ=N", "ABC", 4,409"QUJDQQ=?", "ABC", 4,410};411412Base64.Decoder[] decs = new Base64.Decoder[] {413Base64.getDecoder(),414Base64.getUrlDecoder(),415Base64.getMimeDecoder()416};417418for (Base64.Decoder dec : decs) {419for (int i = 0; i < data.length; i += 3) {420final String srcStr = (String)data[i];421final byte[] srcBytes = srcStr.getBytes("ASCII");422final ByteBuffer srcBB = ByteBuffer.wrap(srcBytes);423byte[] expected = ((String)data[i + 1]).getBytes("ASCII");424int pos = (Integer)data[i + 2];425426// decode(byte[])427checkIAE(() -> dec.decode(srcBytes));428429// decode(String)430checkIAE(() -> dec.decode(srcStr));431432// decode(ByteBuffer)433checkIAE(() -> dec.decode(srcBB));434435// wrap stream436checkIOE(new Testable() {437public void test() throws IOException {438try (InputStream is = dec.wrap(new ByteArrayInputStream(srcBytes))) {439while (is.read() != -1);440}441}});442}443}444445// anything left after padding is "invalid"/IAE, if446// not MIME. In case of MIME, non-base64 character(s)447// is ignored.448checkIAE(() -> Base64.getDecoder().decode("AA==\u00D2"));449checkIAE(() -> Base64.getUrlDecoder().decode("AA==\u00D2"));450Base64.getMimeDecoder().decode("AA==\u00D2");451}452453private static void testDecodeUnpadded() throws Throwable {454byte[] srcA = new byte[] { 'Q', 'Q' };455byte[] srcAA = new byte[] { 'Q', 'Q', 'E'};456Base64.Decoder dec = Base64.getDecoder();457byte[] ret = dec.decode(srcA);458if (ret[0] != 'A')459throw new RuntimeException("Decoding unpadding input A failed");460ret = dec.decode(srcAA);461if (ret[0] != 'A' && ret[1] != 'A')462throw new RuntimeException("Decoding unpadding input AA failed");463ret = new byte[10];464if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 1 &&465ret[0] != 'A')466throw new RuntimeException("Decoding unpadding input A from stream failed");467if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 2 &&468ret[0] != 'A' && ret[1] != 'A')469throw new RuntimeException("Decoding unpadding input AA from stream failed");470}471472// single-non-base64-char should be ignored for mime decoding, but473// iae for basic decoding474private static void testSingleNonBase64MimeDec() throws Throwable {475for (String nonBase64 : new String[] {"#", "(", "!", "\\", "-", "_"}) {476if (Base64.getMimeDecoder().decode(nonBase64).length != 0) {477throw new RuntimeException("non-base64 char is not ignored");478}479try {480Base64.getDecoder().decode(nonBase64);481throw new RuntimeException("No IAE for single non-base64 char");482} catch (IllegalArgumentException iae) {}483}484}485486private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected)487throws Throwable {488489ByteBuffer bout = enc.encode(bin);490byte[] buf = new byte[bout.remaining()];491bout.get(buf);492if (bin.hasRemaining()) {493throw new RuntimeException(494"Base64 enc.encode(ByteBuffer) failed!");495}496checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");497}498499private static final void testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)500throws Throwable {501502ByteBuffer bout = dec.decode(bin);503byte[] buf = new byte[bout.remaining()];504bout.get(buf);505checkEqual(buf, expected, "Base64 dec.decode(bf) failed!");506}507508private static final void checkEqual(int v1, int v2, String msg)509throws Throwable {510if (v1 != v2) {511System.out.printf(" v1=%d%n", v1);512System.out.printf(" v2=%d%n", v2);513throw new RuntimeException(msg);514}515}516517private static final void checkEqual(byte[] r1, byte[] r2, String msg)518throws Throwable {519if (!Arrays.equals(r1, r2)) {520System.out.printf(" r1[%d]=[%s]%n", r1.length, new String(r1));521System.out.printf(" r2[%d]=[%s]%n", r2.length, new String(r2));522throw new RuntimeException(msg);523}524}525526// remove line feeds,527private static final byte[] normalize(byte[] src) {528int n = 0;529boolean hasUrl = false;530for (int i = 0; i < src.length; i++) {531if (src[i] == '\r' || src[i] == '\n')532n++;533if (src[i] == '-' || src[i] == '_')534hasUrl = true;535}536if (n == 0 && hasUrl == false)537return src;538byte[] ret = new byte[src.length - n];539int j = 0;540for (int i = 0; i < src.length; i++) {541if (src[i] == '-')542ret[j++] = '+';543else if (src[i] == '_')544ret[j++] = '/';545else if (src[i] != '\r' && src[i] != '\n')546ret[j++] = src[i];547}548return ret;549}550551private static void testEncoderKeepsSilence(Base64.Encoder enc)552throws Throwable {553List<Integer> vals = new ArrayList<>(List.of(Integer.MIN_VALUE,554Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,555Integer.MAX_VALUE - 1, Integer.MAX_VALUE));556vals.addAll(List.of(rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),557rnd.nextInt()));558byte[] buf = new byte[] {1, 0, 91};559for (int off : vals) {560for (int len : vals) {561if (off >= 0 && len >= 0 && off <= buf.length - len) {562// valid args, skip them563continue;564}565// invalid args, test them566System.out.println("testing off=" + off + ", len=" + len);567568ByteArrayOutputStream baos = new ByteArrayOutputStream(100);569try (OutputStream os = enc.wrap(baos)) {570os.write(buf, off, len);571throw new RuntimeException("Expected IOOBEx was not thrown");572} catch (IndexOutOfBoundsException expected) {573}574if (baos.size() > 0)575throw new RuntimeException("No output was expected, but got "576+ baos.size() + " bytes");577}578}579}580581private static void testDecoderKeepsAbstinence(Base64.Decoder dec)582throws Throwable {583List<Integer> vals = new ArrayList<>(List.of(Integer.MIN_VALUE,584Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,585Integer.MAX_VALUE - 1, Integer.MAX_VALUE));586vals.addAll(List.of(rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),587rnd.nextInt()));588byte[] buf = new byte[3];589for (int off : vals) {590for (int len : vals) {591if (off >= 0 && len >= 0 && off <= buf.length - len) {592// valid args, skip them593continue;594}595// invalid args, test them596System.out.println("testing off=" + off + ", len=" + len);597598String input = "AAAAAAAAAAAAAAAAAAAAAA";599ByteArrayInputStream bais =600new ByteArrayInputStream(input.getBytes("Latin1"));601try (InputStream is = dec.wrap(bais)) {602is.read(buf, off, len);603throw new RuntimeException("Expected IOOBEx was not thrown");604} catch (IndexOutOfBoundsException expected) {605}606if (bais.available() != input.length())607throw new RuntimeException("No input should be consumed, "608+ "but consumed " + (input.length() - bais.available())609+ " bytes");610}611}612}613614private static void testJDK_8222187() throws Throwable {615byte[] orig = "12345678".getBytes("US-ASCII");616byte[] encoded = Base64.getEncoder().encode(orig);617// decode using different buffer sizes, up to a longer one than needed618for (int bufferSize = 1; bufferSize <= encoded.length + 1; bufferSize++) {619try (620InputStream in = Base64.getDecoder().wrap(621new ByteArrayInputStream(encoded));622ByteArrayOutputStream baos = new ByteArrayOutputStream();623) {624byte[] buffer = new byte[bufferSize];625int read;626while ((read = in.read(buffer, 0, bufferSize)) >= 0) {627baos.write(buffer, 0, read);628}629// compare result, output info if lengths do not match630byte[] decoded = baos.toByteArray();631checkEqual(decoded, orig, "Base64 stream decoding failed!");632}633}634}635}636637638