java.security.cert.CertPathValidator Java Examples
The following examples show how to use
java.security.cert.CertPathValidator.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValWithAnchorByName.java From openjdk-jdk9 with GNU General Public License v2.0 | 7 votes |
private static void runTest(CertificateFactory cf, List<X509Certificate> certList, TrustAnchor anchor) throws Exception { CertPath path = cf.generateCertPath(certList); CertPathValidator validator = CertPathValidator.getInstance("PKIX"); System.out.println(anchor); // Attach the OCSP responses to a PKIXParameters object PKIXRevocationChecker pkrev = (PKIXRevocationChecker)validator.getRevocationChecker(); Map<X509Certificate, byte[]> responseMap = new HashMap<>(); responseMap.put(certList.get(0), DECODER.decode(EE_OCSP_RESP)); responseMap.put(certList.get(1), DECODER.decode(INT_CA_OCSP_RESP)); pkrev.setOcspResponses(responseMap); PKIXParameters params = new PKIXParameters(Collections.singleton(anchor)); params.addCertPathChecker(pkrev); params.setDate(EVAL_DATE); validator.validate(path, params); }
Example #2
Source File: KeyManagementUtils.java From cxf with Apache License 2.0 | 6 votes |
private static void validateCertificateChain(KeyStore ks, List<X509Certificate> inCerts, boolean enableRevocation) { // Initial chain validation, to be enhanced as needed try { X509CertSelector certSelect = new X509CertSelector(); certSelect.setCertificate(inCerts.get(0)); PKIXBuilderParameters pbParams = new PKIXBuilderParameters(ks, certSelect); pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(inCerts))); pbParams.setMaxPathLength(-1); pbParams.setRevocationEnabled(false); CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams); pbParams.setRevocationEnabled(enableRevocation); CertPath certPath = buildResult.getCertPath(); CertPathValidator.getInstance("PKIX").validate(certPath, pbParams); } catch (Exception ex) { LOG.warning("Certificate path validation error"); throw new JoseException(ex); } }
Example #3
Source File: CachedCertPathValidator.java From swellrt with Apache License 2.0 | 6 votes |
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); } }
Example #4
Source File: SigningCertificate.java From libsignal-service-java with GNU General Public License v3.0 | 6 votes |
public SigningCertificate(String certificateChain, KeyStore trustStore) throws CertificateException, CertPathValidatorException { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<X509Certificate> certificatesCollection = (Collection<X509Certificate>) certificateFactory.generateCertificates(new ByteArrayInputStream(URLDecoder.decode(certificateChain).getBytes())); List<X509Certificate> certificates = new LinkedList<>(certificatesCollection); PKIXParameters pkixParameters = new PKIXParameters(trustStore); CertPathValidator validator = CertPathValidator.getInstance("PKIX"); this.path = certificateFactory.generateCertPath(certificates); pkixParameters.setRevocationEnabled(false); validator.validate(path, pkixParameters); verifyDistinguishedName(path); } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException e) { throw new AssertionError(e); } }
Example #5
Source File: JKSValidator.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Check if a certificate chain is to be trusted. * * @return true, if validator trusts certificate chain, otherwise false. */ public boolean validateCertificateChain(List<X509Certificate> chain) { if (keystore == null) { return false; } try { CertPath c = getCertificateFactory().generateCertPath(chain); CertPathValidator cpv = getCertPathValidator(); CertPathParameters params = getCertPathParameters(keystore); cpv.validate(c, params); } catch (GeneralSecurityException gse) { if (debug.certificates) { debug.printStackTrace("Failed to validate cert", gse); } // NYI! Log this? return false; } return true; }
Example #6
Source File: GenericX509TrustManager.java From Android-Application-ZJB with Apache License 2.0 | 6 votes |
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { this.mOriginalX509TrustManager.checkServerTrusted(chain, authType); } catch (CertificateException e1) { try { X509Certificate[] ex = this.reorderCertificateChain(chain); CertPathValidator validator = CertPathValidator.getInstance("PKIX"); CertificateFactory factory = CertificateFactory.getInstance("X509"); CertPath certPath = factory.generateCertPath(Arrays.asList(ex)); PKIXParameters params = new PKIXParameters(this.mTrustStore); params.setRevocationEnabled(false); validator.validate(certPath, params); } catch (Exception e) { throw e1; } } }
Example #7
Source File: ExportControlled.java From Komondor with GNU General Public License v3.0 | 6 votes |
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException { this.origTm = tm; this.verifyServerCert = verifyServerCertificate; if (verifyServerCertificate) { try { Set<TrustAnchor> anch = new HashSet<TrustAnchor>(); for (X509Certificate cert : tm.getAcceptedIssuers()) { anch.add(new TrustAnchor(cert, null)); } this.validatorParams = new PKIXParameters(anch); this.validatorParams.setRevocationEnabled(false); this.validator = CertPathValidator.getInstance("PKIX"); this.certFactory = CertificateFactory.getInstance("X.509"); } catch (Exception e) { throw new CertificateException(e); } } }
Example #8
Source File: CachedCertPathValidator.java From incubator-retired-wave with Apache License 2.0 | 6 votes |
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); } }
Example #9
Source File: ExportControlled.java From r-course with MIT License | 6 votes |
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException { this.origTm = tm; this.verifyServerCert = verifyServerCertificate; if (verifyServerCertificate) { try { Set<TrustAnchor> anch = new HashSet<TrustAnchor>(); for (X509Certificate cert : tm.getAcceptedIssuers()) { anch.add(new TrustAnchor(cert, null)); } this.validatorParams = new PKIXParameters(anch); this.validatorParams.setRevocationEnabled(false); this.validator = CertPathValidator.getInstance("PKIX"); this.certFactory = CertificateFactory.getInstance("X.509"); } catch (Exception e) { throw new CertificateException(e); } } }
Example #10
Source File: SigningCertificate.java From mollyim-android with GNU General Public License v3.0 | 6 votes |
public SigningCertificate(String certificateChain, KeyStore trustStore) throws CertificateException, CertPathValidatorException { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<X509Certificate> certificatesCollection = (Collection<X509Certificate>) certificateFactory.generateCertificates(new ByteArrayInputStream(certificateChain.getBytes())); List<X509Certificate> certificates = new LinkedList<>(certificatesCollection); PKIXParameters pkixParameters = new PKIXParameters(trustStore); CertPathValidator validator = CertPathValidator.getInstance("PKIX"); if (certificates.isEmpty()) { throw new CertificateException("No certificates available! Badly-formatted cert chain?"); } this.path = certificateFactory.generateCertPath(certificates); pkixParameters.setRevocationEnabled(false); validator.validate(path, pkixParameters); verifyDistinguishedName(path); } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException e) { throw new AssertionError(e); } }
Example #11
Source File: ValidatePathWithParams.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Constructor * * @param additionalTrustRoots trusted root certificates * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException */ public ValidatePathWithParams(String[] additionalTrustRoots) throws IOException, CertificateException, NoSuchAlgorithmException { cf = CertificateFactory.getInstance("X509"); certPathValidator = CertPathValidator.getInstance("PKIX"); certPathChecker = (PKIXRevocationChecker) certPathValidator.getRevocationChecker(); if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) { trustedRootCerts = null; } else { trustedRootCerts = additionalTrustRoots.clone(); } }
Example #12
Source File: PathCertificateVerifier.java From oxAuth with MIT License | 5 votes |
/** * Attempts to build a certification chain for given certificate to verify * it. Relies on a set of root CA certificates (trust anchors) and a set of * intermediate certificates (to be used as part of the chain). */ private PKIXCertPathBuilderResult verifyCertificate(X509Certificate certificate, Set<X509Certificate> trustedRootCerts, Set<X509Certificate> intermediateCerts) throws GeneralSecurityException { // Create the selector that specifies the starting certificate X509CertSelector selector = new X509CertSelector(); selector.setBasicConstraints(-2); selector.setCertificate(certificate); // Create the trust anchors (set of root CA certificates) Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>(); for (X509Certificate trustedRootCert : trustedRootCerts) { trustAnchors.add(new TrustAnchor(trustedRootCert, null)); } // Configure the PKIX certificate builder algorithm parameters PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector); // Turn off default revocation-checking mechanism pkixParams.setRevocationEnabled(false); // Specify a list of intermediate certificates CertStore intermediateCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts)); pkixParams.addCertStore(intermediateCertStore); // Build and verify the certification chain CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); PKIXCertPathBuilderResult certPathBuilderResult = (PKIXCertPathBuilderResult) builder.build(pkixParams); // Additional check to Verify cert path CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); PKIXCertPathValidatorResult certPathValidationResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPathBuilderResult.getCertPath(), pkixParams); return certPathBuilderResult; }
Example #13
Source File: ValidatePathWithParams.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * Constructor * * @param additionalTrustRoots trusted root certificates * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException */ public ValidatePathWithParams(String[] additionalTrustRoots) throws IOException, CertificateException, NoSuchAlgorithmException { cf = CertificateFactory.getInstance("X509"); certPathValidator = CertPathValidator.getInstance("PKIX"); certPathChecker = (PKIXRevocationChecker) certPathValidator.getRevocationChecker(); if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) { trustedRootCerts = null; } else { trustedRootCerts = additionalTrustRoots.clone(); } }
Example #14
Source File: PKIXChainValidation.java From fido2 with GNU Lesser General Public License v2.1 | 5 votes |
public static boolean pkixvalidate(CertPath cp, Set<TrustAnchor> trustAnchorSet, boolean isRevocationChecked, boolean isPolicyQualifiersRejected) { try { CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); //TODO use BCFIPS when "Support for PKIXRevocationChecker //in the CertPath implementation" is added PKIXParameters pkix = new PKIXParameters(trustAnchorSet); if(isRevocationChecked){ PKIXRevocationChecker prc = (PKIXRevocationChecker) cpv.getRevocationChecker(); prc.setOptions(EnumSet.of(PKIXRevocationChecker.Option.PREFER_CRLS, PKIXRevocationChecker.Option.NO_FALLBACK)); pkix.addCertPathChecker(prc); } else{ pkix.setRevocationEnabled(false); } pkix.setPolicyQualifiersRejected(isPolicyQualifiersRejected); pkix.setDate(null); CertPathValidatorResult cpvr = cpv.validate(cp, pkix); if (cpvr != null) { System.out.println("Certificate validated"); return true; } else { System.out.println("Certificate not valid"); return false; } } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertPathValidatorException ex) { Logger.getLogger(PKIXChainValidation.class.getName()).log(Level.SEVERE, null, ex); return false; } }
Example #15
Source File: ServerCrypto.java From carbon-identity with Apache License 2.0 | 5 votes |
private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException { try { // Generate cert path java.util.List certList = java.util.Arrays.asList(certs); CertPath path = this.getCertificateFactory().generateCertPath(certList); // Use the certificates in the keystore as TrustAnchors PKIXParameters param = new PKIXParameters(ks); // Do not check a revocation list param.setRevocationEnabled(false); // Verify the trust path using the above settings String provider = properties .getProperty("org.apache.ws.security.crypto.merlin.cert.provider"); CertPathValidator certPathValidator; if (provider == null || provider.length() == 0) { certPathValidator = CertPathValidator.getInstance("PKIX"); } else { certPathValidator = CertPathValidator.getInstance("PKIX", provider); } certPathValidator.validate(path, param); } catch (NoSuchProviderException | NoSuchAlgorithmException | CertificateException | InvalidAlgorithmParameterException | CertPathValidatorException | KeyStoreException ex) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[]{ex.getMessage()}, ex); } return true; }
Example #16
Source File: XMLDSigVerifier.java From alpha-wallet-android with MIT License | 5 votes |
private void validateCertificateChain(List<X509Certificate> certList) throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException, CertificateException, CertPathValidatorException { // By default on Oracle JRE, algorithm is PKIX TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); // 'null' will initialise the tmf with the default CA certs installed // with the JRE. tmf.init((KeyStore) null); X509TrustManager tm = (X509TrustManager) tmf.getTrustManagers()[0]; CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); Set<TrustAnchor> anch = new HashSet<>(); for (X509Certificate cert : tm.getAcceptedIssuers()) { anch.add(new TrustAnchor(cert, null)); } PKIXParameters params = new PKIXParameters(anch); Security.setProperty("ocsp.enable", "true"); params.setRevocationEnabled(true); CertificateFactory factory = CertificateFactory.getInstance("X.509"); try { cpv.validate(factory.generateCertPath(certList), params); } catch (CertPathValidatorException e) { System.out.println(e.getIndex()); //if the timestamp check fails because the cert is expired //we allow this to continue (code 0) if(e.getIndex() != 0) { throw e; } } }
Example #17
Source File: ValidatePathWithParams.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Constructor * * @param additionalTrustRoots trusted root certificates * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException */ public ValidatePathWithParams(String[] additionalTrustRoots) throws IOException, CertificateException, NoSuchAlgorithmException { cf = CertificateFactory.getInstance("X509"); certPathValidator = CertPathValidator.getInstance("PKIX"); certPathChecker = (PKIXRevocationChecker) certPathValidator.getRevocationChecker(); if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) { trustedRootCerts = null; } else { trustedRootCerts = additionalTrustRoots.clone(); } }
Example #18
Source File: SparkExceptionsTrustManager.java From Spark with Apache License 2.0 | 5 votes |
/** * Validate certificate path. As it is exception, no checks against revocation or time validity are done but path * still have to be validated in order to find connection between certificate presented by server and root CA in * KeyStore * * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws InvalidAlgorithmParameterException * @throws CertPathValidatorException * @throws CertPathBuilderException * @throws CertificateException */ private void validatePath(X509Certificate[] chain) throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException, CertPathValidatorException, CertPathBuilderException, CertificateException { CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX"); CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX"); X509CertSelector certSelector = new X509CertSelector(); certSelector.setCertificate(chain[chain.length - 1]); // checks against time validity aren't done here as it exceptions list certSelector.setCertificateValid(null); PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector); // no checks against revocation as it is exception parameters.setRevocationEnabled(false); CertPathBuilderResult pathResult = certPathBuilder.build(parameters); CertPath certPath = pathResult.getCertPath(); PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator .validate(certPath, parameters); X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert(); if (trustedCert == null) { throw new CertificateException("Certificate path failed"); } else { Log.debug("ClientTrustManager: Trusted CA: " + trustedCert.getSubjectDN()); } }
Example #19
Source File: ValidatePathWithParams.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
/** * Constructor * * @param additionalTrustRoots trusted root certificates * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException */ public ValidatePathWithParams(String[] additionalTrustRoots) throws IOException, CertificateException, NoSuchAlgorithmException { cf = CertificateFactory.getInstance("X509"); certPathValidator = CertPathValidator.getInstance("PKIX"); certPathChecker = (PKIXRevocationChecker) certPathValidator.getRevocationChecker(); if ((additionalTrustRoots == null) || (additionalTrustRoots[0] == null)) { trustedRootCerts = null; } else { trustedRootCerts = additionalTrustRoots.clone(); } }
Example #20
Source File: JKSValidator.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * */ private CertPathValidator getCertPathValidator() throws GeneralSecurityException { if (certValidator == null) { if (certProvider.length() > 0) { certValidator = CertPathValidator.getInstance("PKIX", certProvider); } else { certValidator = CertPathValidator.getInstance("PKIX"); } } return certValidator; }
Example #21
Source File: CryptoPrimitives.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
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; }
Example #22
Source File: CertificateValidator.java From WebSocket-for-Android with Apache License 2.0 | 4 votes |
public void validate(Certificate[] certChain) throws CertificateException { try { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); for (Certificate item : certChain) { if (item == null) continue; if (!(item instanceof X509Certificate)) { throw new IllegalStateException("Invalid certificate type in chain"); } certList.add((X509Certificate)item); } if (certList.isEmpty()) { throw new IllegalStateException("Invalid certificate chain"); } X509CertSelector certSelect = new X509CertSelector(); certSelect.setCertificate(certList.get(0)); // Configure certification path builder parameters PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect); pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList))); // Set maximum certification path length pbParams.setMaxPathLength(_maxCertPathLength); // Enable revocation checking pbParams.setRevocationEnabled(true); // Set static Certificate Revocation List if (_crls != null && !_crls.isEmpty()) { pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls))); } // Enable On-Line Certificate Status Protocol (OCSP) support if (_enableOCSP) { Security.setProperty("ocsp.enable","true"); } // Enable Certificate Revocation List Distribution Points (CRLDP) support if (_enableCRLDP) { System.setProperty("com.sun.security.enableCRLDP","true"); } // Build certification path CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams); // Validate certification path CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams); } catch (GeneralSecurityException gse) { LOG.debug(gse); throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse); } }
Example #23
Source File: CertificateUtilTest.java From webauthn4j with Apache License 2.0 | 4 votes |
@Test void generateCertPathValidator_test() { CertPathValidator certPathValidator = CertificateUtil.createCertPathValidator(); assertThat(certPathValidator).isNotNull(); }
Example #24
Source File: CertificateValidator.java From IoTgo_Android_App with MIT License | 4 votes |
public void validate(Certificate[] certChain) throws CertificateException { try { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); for (Certificate item : certChain) { if (item == null) continue; if (!(item instanceof X509Certificate)) { throw new IllegalStateException("Invalid certificate type in chain"); } certList.add((X509Certificate)item); } if (certList.isEmpty()) { throw new IllegalStateException("Invalid certificate chain"); } X509CertSelector certSelect = new X509CertSelector(); certSelect.setCertificate(certList.get(0)); // Configure certification path builder parameters PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect); pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList))); // Set maximum certification path length pbParams.setMaxPathLength(_maxCertPathLength); // Enable revocation checking pbParams.setRevocationEnabled(true); // Set static Certificate Revocation List if (_crls != null && !_crls.isEmpty()) { pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls))); } // Enable On-Line Certificate Status Protocol (OCSP) support if (_enableOCSP) { Security.setProperty("ocsp.enable","true"); } // Enable Certificate Revocation List Distribution Points (CRLDP) support if (_enableCRLDP) { System.setProperty("com.sun.security.enableCRLDP","true"); } // Build certification path CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams); // Validate certification path CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams); } catch (GeneralSecurityException gse) { LOG.debug(gse); throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse); } }
Example #25
Source File: CertificateValidator.java From IoTgo_Android_App with MIT License | 4 votes |
public void validate(Certificate[] certChain) throws CertificateException { try { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); for (Certificate item : certChain) { if (item == null) continue; if (!(item instanceof X509Certificate)) { throw new IllegalStateException("Invalid certificate type in chain"); } certList.add((X509Certificate)item); } if (certList.isEmpty()) { throw new IllegalStateException("Invalid certificate chain"); } X509CertSelector certSelect = new X509CertSelector(); certSelect.setCertificate(certList.get(0)); // Configure certification path builder parameters PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect); pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList))); // Set maximum certification path length pbParams.setMaxPathLength(_maxCertPathLength); // Enable revocation checking pbParams.setRevocationEnabled(true); // Set static Certificate Revocation List if (_crls != null && !_crls.isEmpty()) { pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls))); } // Enable On-Line Certificate Status Protocol (OCSP) support if (_enableOCSP) { Security.setProperty("ocsp.enable","true"); } // Enable Certificate Revocation List Distribution Points (CRLDP) support if (_enableCRLDP) { System.setProperty("com.sun.security.enableCRLDP","true"); } // Build certification path CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams); // Validate certification path CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams); } catch (GeneralSecurityException gse) { LOG.debug(gse); throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse); } }
Example #26
Source File: SparkTrustManager.java From Spark with Apache License 2.0 | 4 votes |
/** * Validate certificate path * * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws InvalidAlgorithmParameterException * @throws CertPathValidatorException * @throws CertPathBuilderException * @throws CertificateException */ private void validatePath(X509Certificate[] chain) throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException, CertPathValidatorException, CertPathBuilderException, CertificateException { // PKIX algorithm is defined in rfc3280 CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX"); CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX"); X509CertSelector certSelector = new X509CertSelector(); // set last certificate (often root CA) from chain for CertSelector so trust store must contain it certSelector.setCertificate(chain[chain.length - 1]); // checks against time validity aren't done here as are already done in checkDateValidity (X509Certificate[] // chain) certSelector.setCertificateValid(null); // create parameters using trustStore as source of Trust Anchors and using X509CertSelector PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector); // will use PKIXRevocationChecker (or nothing if revocation mechanisms are // disabled) instead of the default revocation checker parameters.setRevocationEnabled(false); // if revoked certificates aren't accepted, but no revocation checks then only // certificates from blacklist will be rejected if (acceptRevoked == false) { // OCSP checking is done according to Java PKI Programmer's Guide, PKIXRevocationChecker was added in Java 8: // https://docs.oracle.com/javase/8/docs/technotes/guides/security/certpath/CertPathProgGuide.html#PKIXRevocationChecker PKIXRevocationChecker checker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker(); EnumSet<PKIXRevocationChecker.Option> checkerOptions = EnumSet.noneOf(PKIXRevocationChecker.Option.class); // if soft fail isn't enabled then OCSP or CRL must pass validation, in case // when any of them cannot be validated verification will fail, if soft fail // is enabled then in case of network issues revocation checking is omitted if (allowSoftFail) { checkerOptions.add(PKIXRevocationChecker.Option.SOFT_FAIL); } // check OCSP, CRL serve as backup if (checkOCSP && checkCRL) { checker.setOptions(checkerOptions); parameters.addCertPathChecker(checker); } else if (!checkOCSP && checkCRL) { // check only CRL, if CRL fail then there is no fallback to OCSP checkerOptions.add(PKIXRevocationChecker.Option.PREFER_CRLS); checkerOptions.add(PKIXRevocationChecker.Option.NO_FALLBACK); checker.setOptions(checkerOptions); parameters.addCertPathChecker(checker); } } try { CertPathBuilderResult pathResult = certPathBuilder.build(parameters); CertPath certPath = pathResult.getCertPath(); PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator .validate(certPath, parameters); X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert(); if (trustedCert == null) { throw new CertificateException("certificate path failed: Trusted CA is NULL"); } // check if all certificates in path have Basic Constraints, only certificate that isn't required to have // this extension is last certificate: root CA for (int i = 0; i < chain.length - 1; i++) { checkBasicConstraints(chain[i]); } } catch (CertificateRevokedException e) { Log.warning("Certificate was revoked", e); for (X509Certificate cert : chain) { for (X509CRL crl : crlCollection) { if (crl.isRevoked(cert)) { try { addToBlackList(cert); } catch (IOException | HeadlessException | InvalidNameException e1) { Log.error("Couldn't move to the blacklist", e1); } break; } } } throw new CertificateException("Certificate was revoked"); } }
Example #27
Source File: ExtensionsWithLDAP.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { String extension = args[0]; String targetHost = args[1]; // enable CRLDP and AIA extensions System.setProperty("com.sun.security.enableCRLDP", "true"); System.setProperty("com.sun.security.enableAIAcaIssuers", "true"); Path hostsFilePath = Paths.get(System.getProperty("test.src", ".") + File.separator + extension); System.setProperty("jdk.net.hosts.file", hostsFilePath.toFile().getAbsolutePath()); X509Certificate trustedCert = loadCertificate(CA_CERT); X509Certificate eeCert = loadCertificate(EE_CERT); Set<TrustAnchor> trustedCertsSet = new HashSet<>(); trustedCertsSet.add(new TrustAnchor(trustedCert, null)); CertPath cp = (CertPath) CertificateFactory.getInstance("X509") .generateCertPath(Arrays.asList(eeCert)); // CertPath validator should try to parse CRLDP and AIA extensions, // and load CRLs/certs which they point to. // If proxy server catches requests for resolving host names // which extensions contain, then it means that CertPath validator // tried to load CRLs/certs which they point to. List<String> hosts = new ArrayList<>(); Consumer<Socket> socketConsumer = (Socket socket) -> { InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); hosts.add(remoteAddress.getHostName()); }; try (SocksProxy proxy = SocksProxy.startProxy(socketConsumer)) { CertPathValidator.getInstance("PKIX").validate(cp, new PKIXParameters(trustedCertsSet)); throw new RuntimeException("CertPathValidatorException not thrown"); } catch (CertPathValidatorException cpve) { System.out.println("Expected exception: " + cpve); } if (!hosts.contains(targetHost)) { throw new RuntimeException( String.format("The %s from %s extension is not requested", targetHost, extension)); } System.out.println("Test passed"); }
Example #28
Source File: SSLSocketWithStapling.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * Test a case where client-side stapling is attempted, but does not * occur because OCSP responders are unreachable. Client-side OCSP * checking is enabled for this, with SOFT_FAIL. */ static void testSoftFailFallback() throws Exception { ClientParameters cliParams = new ClientParameters(); ServerParameters servParams = new ServerParameters(); serverReady = false; // make OCSP responders reject connections intOcsp.rejectConnections(); rootOcsp.rejectConnections(); System.out.println("======================================="); System.out.println("Stapling enbled in client and server,"); System.out.println("but OCSP responders disabled."); System.out.println("PKIXParameters with Revocation checking"); System.out.println("enabled and SOFT_FAIL."); System.out.println("======================================="); Security.setProperty("ocsp.enable", "true"); cliParams.pkixParams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); cliParams.pkixParams.setRevocationEnabled(true); CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); cliParams.revChecker = (PKIXRevocationChecker)cpv.getRevocationChecker(); cliParams.revChecker.setOptions(EnumSet.of(Option.SOFT_FAIL)); SSLSocketWithStapling sslTest = new SSLSocketWithStapling(cliParams, servParams); TestResult tr = sslTest.getResult(); if (tr.clientExc != null) { throw tr.clientExc; } else if (tr.serverExc != null) { throw tr.serverExc; } System.out.println(" PASS"); System.out.println("=======================================\n"); // Make OCSP responders accept connections intOcsp.acceptConnections(); rootOcsp.acceptConnections(); // Wait 5 seconds for server ready for (int i = 0; (i < 100 && (!intOcsp.isServerReady() || !rootOcsp.isServerReady())); i++) { Thread.sleep(50); } if (!intOcsp.isServerReady() || !rootOcsp.isServerReady()) { throw new RuntimeException("Server not ready yet"); } }
Example #29
Source File: CertificateValidator.java From cloudhopper-commons with Apache License 2.0 | 4 votes |
public void validate(Certificate[] certChain) throws CertificateException { try { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); for (Certificate item : certChain) { if (item == null) continue; if (!(item instanceof X509Certificate)) { throw new IllegalStateException("Invalid certificate type in chain"); } certList.add((X509Certificate)item); } if (certList.isEmpty()) { throw new IllegalStateException("Invalid certificate chain"); } X509CertSelector certSelect = new X509CertSelector(); certSelect.setCertificate(certList.get(0)); // Configure certification path builder parameters PKIXBuilderParameters pbParams = new PKIXBuilderParameters(trustStore, certSelect); pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList))); // Set maximum certification path length pbParams.setMaxPathLength(maxCertPathLength); // Enable revocation checking pbParams.setRevocationEnabled(true); // Set static Certificate Revocation List if (crls != null && !crls.isEmpty()) { pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls))); } // Enable On-Line Certificate Status Protocol (OCSP) support if (enableOCSP) { Security.setProperty("ocsp.enable","true"); } // Enable Certificate Revocation List Distribution Points (CRLDP) support if (enableCRLDP) { System.setProperty("com.sun.security.enableCRLDP","true"); } // Build certification path CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams); // Validate certification path CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams); } catch (GeneralSecurityException gse) { logger.debug("", gse); throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse); } }
Example #30
Source File: ValidateTargetConstraints.java From jdk8u_jdk with GNU General Public License v2.0 | 3 votes |
/** * Perform a PKIX validation. * * @param path CertPath to validate * @param params PKIXParameters to use in validation * @throws Exception on error */ public static void validate(CertPath path, PKIXParameters params) throws Exception { CertPathValidator validator = CertPathValidator.getInstance("PKIX"); CertPathValidatorResult cpvr = validator.validate(path, params); }