### Question:
DefaultCertificateValidator implements CertificateValidator { @Override public boolean validate(final List<byte[]> certificates) { try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final List<X509Certificate> certlist = certificates .stream() .map( bytes -> { try { return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } }) .collect(Collectors.toUnmodifiableList()); final CertPath cp = cf.generateCertPath(certlist); final PKIXParameters params = new PKIXParameters(truststore); params.setRevocationEnabled(false); final CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); cpv.validate(cp, params); return true; } catch (final CertPathValidatorException e) { return false; } catch (final GeneralSecurityException e) { throw new RuntimeException(e); } } DefaultCertificateValidator(final KeyStore truststore); @Override boolean validate(final List<byte[]> certificates);  }### Answer:
@Test public void google() throws IOException { final CertificateValidator validator = CertificateValidator.defaults(); final byte[] cert1 = Files.readAllBytes(new File("src/test/resources/google1.crt").toPath()); final byte[] cert2 = Files.readAllBytes(new File("src/test/resources/google2.crt").toPath()); assertTrue(validator.validate(List.of(cert1, cert2))); }
@Test public void googleMissingIntermediate() throws IOException { final CertificateValidator validator = CertificateValidator.defaults(); final byte[] cert1 = Files.readAllBytes(new File("src/test/resources/google1.crt").toPath()); assertFalse(validator.validate(List.of(cert1))); }
@Test public void selfSigned() throws GeneralSecurityException, IOException { final KeyStore truststore = KeyStore.getInstance("JKS"); final X509Certificate cert = KeyUtil.getCertFromCrt("src/test/resources/server.crt"); truststore.load(() -> new KeyStore.PasswordProtection("hello".toCharArray())); truststore.setCertificateEntry("pwn", cert); final CertificateValidator validator = new DefaultCertificateValidator(truststore); final byte[] certBytes = Files.readAllBytes(new File("src/test/resources/server.crt").toPath()); assertTrue(validator.validate(List.of(certBytes))); }
@Test public void selfSignedNotTrusted() throws IOException { final CertificateValidator validator = CertificateValidator.defaults(); final byte[] certBytes = Files.readAllBytes(new File("src/test/resources/server.crt").toPath()); assertFalse(validator.validate(List.of(certBytes))); }