KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = "changeit"; keystore.load(is, password.toCharArray()); PKIXParameters params = new PKIXParameters(keystore); Iterator it = params.getTrustAnchors().iterator(); while( it.hasNext() ) { TrustAnchor ta = (TrustAnchor)it.next(); X509Certificate cert = ta.getTrustedCert(); System.out.println(cert);
CertificateFactory cf = CertificateFactory.getInstance("X.509"); DERObject certObj = (DERObject) certificates.nextElement(); InputStream in = new ByteArrayInputStream(certObj.getDEREncoded()); certList.add(cf.generateCertificate(in)); CertPath certPath = cf.generateCertPath(certList); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keyStorePath), null); PKIXParameters params = new PKIXParameters(keyStore); params.setRevocationEnabled(false); // to avoid exception on empty CRL CertPathValidator validator = CertPathValidator.getInstance("PKIX"); CertPathValidatorResult result = validator.validate(certPath, params);
/** * Creates a new {@code PKIXBuilderParameters} instance with the specified * set of {@code TrustAnchor} and certificate constraints. * * @param trustAnchors * the set of {@code TrustAnchors}. * @param targetConstraints * the certificate constraints. * @throws InvalidAlgorithmParameterException * if {@code trustAnchors} is empty. * @throws ClassCastException * if one of the items in {@code trustAnchors} is not an * instance of {@code java.security.cert.TrustAnchor}. */ public PKIXBuilderParameters(Set<TrustAnchor> trustAnchors, CertSelector targetConstraints) throws InvalidAlgorithmParameterException { super(trustAnchors); super.setTargetCertConstraints(targetConstraints); }
Iterator anchors = pkixParams.getTrustAnchors().iterator(); if (!anchors.hasNext()) { throw new CertPathValidatorException( currCert.getIssuerX500Principal(); while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) { X509Certificate anchorCert = anchor.getTrustedCert(); X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal(); throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN()); filter.setSubject(responderSubjectName.getName()); List<CertStore> certStores = pkixParams.getCertStores(); for (CertStore certStore : certStores) { Iterator i = certStore.getCertificates(filter).iterator();
X509Certificate certToVerify = ... CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath cp = cf.generateCertPath(Arrays .asList(new X509Certificate[] { certToVerify })); TrustAnchor trustAnchor = new TrustAnchor(caCert, null); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXParameters pkixParams = new PKIXParameters( Collections.singleton(trustAnchor)); pkixParams.setRevocationEnabled(false); cpv.validate(cp, pkixParams);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); Path ksPath = Paths.get(System.getProperty("java.home"), "lib", "security", "cacerts"); keyStore.load(Files.newInputStream(ksPath), "changeit".toCharArray()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); try (InputStream caInput = new BufferedInputStream( Certificate crt = cf.generateCertificate(caInput); System.out.println("Added Cert for " + ((X509Certificate) crt) .getSubjectDN()); keyStore.setCertificateEntry("DSTRootCAX3", crt); PKIXParameters params = new PKIXParameters(keyStore); params.getTrustAnchors().stream() .map(TrustAnchor::getTrustedCert)
KeyManagementException { String keyStoreType = KeyStore.getDefaultType(); final KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("CAcert-root", getCertificate(CACERTROOTDER)); X509Certificate cert = chain[0]; cert.checkValidity(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(); list.add(cert); CertPath cp = cf.generateCertPath(list); try { PKIXParameters params = new PKIXParameters(keyStore); params.setRevocationEnabled(false); // CLR is broken, remember? CertPathValidator cpv = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); cpv.validate(cp, params); } catch (KeyStoreException e) { Log.d(TAG, "invalid key store", e);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = "changeit"; keystore.load(is, password.toCharArray()); PKIXParameters params = new PKIXParameters(keystore); Iterator it = params.getTrustAnchors().iterator(); while( it.hasNext() ) { TrustAnchor ta = (TrustAnchor)it.next(); xroot = ta.getTrustedCert(); try{ cc.verify(xroot.getPublicKey()); break;
boolean validateCertificate(Certificate cert) { boolean isValidated; if (cert == null) { return false; } try { KeyStore keyStore = getTrustStore(); PKIXParameters parms = new PKIXParameters(keyStore); parms.setRevocationEnabled(false); CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // PKIX ArrayList<Certificate> start = new ArrayList<>(); start.add(cert); CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT); CertPath certPath = certFactory.generateCertPath(start); certValidator.validate(certPath, parms); isValidated = true; } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | CertificateException | CertPathValidatorException | CryptoException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate" + cert.toString()); isValidated = false; } return isValidated; } // validateCertificate
CertificateFactory cf = CertificateFactory.getInstance("X.509"); List<Certificate> certx = new ArrayList<>(certChain.length); for (byte[] c : certChain) certx.add(cf.generateCertificate(new ByteArrayInputStream(c))); CertPath path = cf.generateCertPath(certx); CertPathValidator validator = CertPathValidator.getInstance("PKIX"); KeyStore keystore = KeyStore.getInstance("JKS"); try (InputStream is = Files.newInputStream(Paths.get("cacerts.jks"))) { keystore.load(is, "changeit".toCharArray()); } Collection<? extends CRL> crls; try (InputStream is = Files.newInputStream(Paths.get("crls.p7c"))) { crls = cf.generateCRLs(is); } PKIXParameters params = new PKIXParameters(keystore); CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)); /* If necessary, specify the certificate policy or other requirements * with the appropriate params.setXXX() method. */ params.addCertStore(store); /* Validate will throw an exception on invalid chains. */ PKIXCertPathValidatorResult r = (PKIXCertPathValidatorResult) validator.validate(path, params);
try { KeyStore cacerts = KeyStore.getInstance("JKS"); cacerts.load(new FileInputStream(new File(System.getProperty("java.home"), "lib/security/cacerts")), null); params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(certs)))); params.setRevocationEnabled(false); CertPath cp = CertPathBuilder.getInstance("PKIX").build(params).getCertPath(); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) CertPathValidator.getInstance("PKIX").validate(cp, params); return isEV(result); } catch (Exception ex) { X500Principal root = result.getTrustAnchor().getTrustedCert().getSubjectX500Principal(); System.out.println("[Debug] Found root DN: "+root.getName()); String policy = policies.get(root);
/** * This creates a verification instance that will check the validation of a certificate * against the Java runtime's trusted CA certs keystore. * @param enableRevocation * @throws IOException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws InvalidAlgorithmParameterException */ public X509HostKeyVerification(boolean enableRevocation) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, InvalidAlgorithmParameterException { String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar); FileInputStream is = new FileInputStream(filename); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = "changeit"; keystore.load(is, password.toCharArray()); params = new PKIXParameters(keystore); params.setRevocationEnabled(enableRevocation); }
/** * Validates a chain of {@link X509Certificate}s. * * @param certificateList The certificate list * @param anchor The anchor * @throws CertificateException e * @throws NoSuchAlgorithmException e * @throws InvalidAlgorithmParameterException e * @throws CertPathValidatorException e * @throws IOException */ public static void validateChain(List<Certificate> certificateList, X509Certificate anchor) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, CertPathValidatorException, IOException { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // Convert into a list of X509Certificates List<X509Certificate> certsList = new ArrayList<>(certificateList.size()); for (Certificate cert : certificateList) { X509Certificate parsedCert = (X509Certificate) certificateFactory.generateCertificate( new ByteArrayInputStream(cert.encode())); certsList.add(parsedCert); } CertPath certPath = certificateFactory.generateCertPath(certsList); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); TrustAnchor trustAnchor = new TrustAnchor(anchor, null); PKIXParameters parameters = new PKIXParameters(Collections.singleton(trustAnchor)); parameters.setRevocationEnabled(false); cpv.validate(certPath, parameters); }
KeyStore ts = KeyStore.getInstance("JKS"); FileInputStream tfis = new FileInputStream(trustStorePath); ts.load(tfis, trustStorePass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // initialize certification path checking for the offered certificates and revocation checks against CLRs CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX"); PKIXRevocationChecker rc = (PKIXRevocationChecker)cpb.getRevocationChecker(); rc.setOptions(EnumSet.of( PKIXRevocationChecker.Option.PREFER_CRLS, // prefer CLR over OCSP PKIXRevocationChecker.Option.ONLY_END_ENTITY, PKIXRevocationChecker.Option.SOFT_FAIL, // handshake should not fail when CRL is not available PKIXRevocationChecker.Option.NO_FALLBACK)); // don't fall back to OCSP checking PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(ts, new X509CertSelector()); pkixParams.addCertPathChecker(rc); tmf.init( new CertPathTrustManagerParameters(pkixParams) ); // init KeyManagerFactory kmf.init(...) SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(kmf.getKeyManagers), tmf.getTrustManagers(), null);
/* Givens. */ InputStream trustStoreInput = ... char[] password = ... List<X509Certificate> chain = ... Collection<X509CRL> crls = ... /* Construct a valid path. */ KeyStore anchors = KeyStore.getInstance(KeyStore.getDefaultType()); anchors.load(trustStoreInput, password); X509CertSelector target = new X509CertSelector(); target.setCertificate(chain.get(0)); PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, target); CertStoreParameters intermediates = new CollectionCertStoreParameters(chain) params.addCertStore(CertStore.getInstance("Collection", intermediates)); CertStoreParameters revoked = new CollectionCertStoreParameters(crls); params.addCertStore(CertStore.getInstance("Collection", revoked)); CertPathBuilder builder = CertPathBuilder.getInstance("PKIX"); /* * If build() returns successfully, the certificate is valid. More details * about the valid path can be obtained through the PKIXBuilderResult. * If no valid path can be found, a CertPathBuilderException is thrown. */ PKIXBuilderResult r = (PKIXBuilderResult) builder.build(params);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<X509Certificate> certs = Lists.newArrayList(); for (ByteString bytes : protoCerts.getCertificateList()) certs.add((X509Certificate) certificateFactory.generateCertificate(bytes.newInput())); CertPath path = certificateFactory.generateCertPath(certs); PKIXParameters params = new PKIXParameters(createKeyStore(trustStorePath)); params.setRevocationEnabled(false); CertPathValidator validator = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(path, params); PublicKey publicKey = result.getPublicKey(); X500Principal principal = cert.getSubjectX500Principal(); final Iterator<List<?>> it = cert.getSubjectAlternativeNames().iterator(); List<?> list;
private void validateNoCache(List<? extends X509Certificate> certs) throws SignatureException { try { CertPathValidator validator = CertPathValidator.getInstance( VALIDATOR_TYPE); PKIXParameters params = new PKIXParameters(trustRoots); params.addCertPathChecker(WAVE_OID_CHECKER); params.setDate(timeSource.now()); // turn off default revocation-checking mechanism params.setRevocationEnabled(false); // TODO: add a way for clients to add certificate revocation checks, // perhaps by letting them pass in PKIXCertPathCheckers. This can also be // useful to check for Wave-specific certificate extensions. CertificateFactory certFactory = CertificateFactory.getInstance( CERTIFICATE_TYPE); CertPath certPath = certFactory.generateCertPath(certs); validator.validate(certPath, params); } catch (GeneralSecurityException e) { throw new SignatureException("Certificate validation failure", e); } }
try { CertificateFactory certFact = CertificateFactory .getInstance("X.509"); certPath = certFact.generateCertPath(Arrays.asList(certificate)); } catch (CertificateEncodingException e) { logger.error(e.getMessage()); logger.trace("Certificates from truststore:"); Certificate crt = trustStore.getCertificate(alias); if (crt != null) { logger.trace(alias + " is a certificate of type " PKIXParameters params = new PKIXParameters(trustStore); params.setRevocationEnabled(false); .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate( certPath, params); if (logger.isTraceEnabled()) {
String issuerString = certs[0].getIssuerX500Principal().getName(); BigInteger issuerSerial = certs[0].getSerialNumber(); if (foundCerts != null && foundCerts[0] != null && foundCerts[0].equals(certs[0])) { LOG.debug( "Direct trust for certificate with {}", certs[0].getSubjectX500Principal().getName() for (X509Certificate cert : trustedCerts) { TrustAnchor anchor = new TrustAnchor(cert, null); set.add(anchor); PKIXParameters param = new PKIXParameters(set); param.setRevocationEnabled(enableRevocation); CertPath path = getCertificateFactory().generateCertPath(certList); validator.validate(path, param); } else { List<X509Certificate> certList = Arrays.asList(certs); CertPath path = getCertificateFactory().generateCertPath(certList); validator.validate(path, param);
public X509Certificate verifyAttestationCertificates(List<X509Certificate> certs, List<X509Certificate> trustChainCertificates) { try { checkForTrustedCertsInAttestation(certs, trustChainCertificates); Set<TrustAnchor> trustAnchors = trustChainCertificates.parallelStream().map(f -> new TrustAnchor(f, null)).collect(Collectors.toSet()); PKIXParameters params = new PKIXParameters(trustAnchors); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXRevocationChecker rc = (PKIXRevocationChecker) cpv.getRevocationChecker(); rc.setOptions(EnumSet.of(PKIXRevocationChecker.Option.SOFT_FAIL, PKIXRevocationChecker.Option.PREFER_CRLS)); params.addCertPathChecker(rc); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); CertPath certPath = certFactory.generateCertPath(certs); return cert; } else { params = new PKIXParameters(trustAnchors); cpv = CertPathValidator.getInstance("PKIX"); rc = (PKIXRevocationChecker) cpv.getRevocationChecker(); rc.setOptions(Collections.emptySet()); params.setRevocationEnabled(false); params.addCertPathChecker(null);