Example usage for java.security.cert CertPathValidator getInstance

List of usage examples for java.security.cert CertPathValidator getInstance

Introduction

In this page you can find the example usage for java.security.cert CertPathValidator getInstance.

Prototype

public static CertPathValidator getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a CertPathValidator object that implements the specified algorithm.

Usage

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Validate the certificate path using a provided OCSP responder configuration.
 *
 * @param certPath      required//from w w w  .ja v  a 2  s .  com
 * @param crlCollection
 * @param certStore     null possible cert store for PKIX param
 * @param altOCSP       null possible
 * @throws CertificateRevocationCheckException
 * @throws IdmCertificateRevokedException
 */
private void validateCertPath(CertPath certPath, Collection<Object> crlCollection, CertStore certStore,
        AlternativeOCSP altOCSP) throws CertificateRevocationCheckException, IdmCertificateRevokedException {

    setupOCSPOptions(certPath, altOCSP);
    PKIXParameters params = createPKIXParameters(crlCollection);

    if (null != certStore) {
        params.addCertStore(certStore);
    }

    CertPathValidator certPathValidator;
    try {
        certPathValidator = CertPathValidator.getInstance("PKIX");
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateRevocationCheckException("Error getting PKIX validator instance:" + e.getMessage(),
                e);
    }

    try {
        String pkiParam = params.toString();
        logger.trace("**Certificate Path Validation Parameters trust anchors **\n"
                + params.getTrustAnchors().toString() + "\n");

        logger.trace("**Certificate Path Validation Parameters **\n" + pkiParam + "\n");

        CertPathValidatorResult result = certPathValidator.validate(certPath, params);

        logger.trace("**Certificate Path Validation Result **\n" + result.toString() + "\n");
    } catch (CertPathValidatorException e) {
        if (e.getReason() == CertPathValidatorException.BasicReason.REVOKED) {
            throw new IdmCertificateRevokedException("CRL shows certificate status as revoked");
        } else if (e.getReason() == CertPathValidatorException.BasicReason.UNDETERMINED_REVOCATION_STATUS) {
            throw new CertRevocationStatusUnknownException(
                    "CRL checking could not determine certificate status.");
        }
        throw new CertificateRevocationCheckException("Certificate path validation failed:" + e.getMessage(),
                e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateRevocationCheckException(
                "Certificate validation parameters invalid, could not validate certificate path:"
                        + e.getMessage(),
                e);
    }

}

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature//from   w  w  w. j a  v  a 2 s. c o m
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Verifies the signature on an enveloped digital signature on a UDDI
 * entity, such as a business, service, tmodel or binding template.
 * <br><Br>//ww w .ja va2  s  . co m
 * It is expected that either the public key of the signing certificate
 * is included within the signature keyinfo section OR that sufficient
 * information is provided in the signature to reference a public key
 * located within the Trust Store provided<br><Br> Optionally, this
 * function also validate the signing certificate using the options
 * provided to the configuration map.
 *
 * @param obj an enveloped signed JAXB object
 * @param OutErrorMessage a human readable error message explaining the
 * reason for failure
 * @return true if the validation passes the signature validation test,
 * and optionally any certificate validation or trust chain validation
 * @throws IllegalArgumentException for null input
 */
public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage)
        throws IllegalArgumentException {
    if (OutErrorMessage == null) {
        OutErrorMessage = new AtomicReference<String>();
        OutErrorMessage.set("");
    }
    if (obj == null) {
        throw new IllegalArgumentException("obj");
    }
    try {
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);

        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement(); //this is our signed node

        X509Certificate signingcert = getSigningCertificatePublicKey(docElement);

        if (signingcert != null) {
            logger.info(
                    "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString());
            if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) {
                signingcert.checkValidity();
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) {
                logger.info("verifying revocation status via OSCP for X509 public key "
                        + signingcert.getSubjectDN().toString());
                X500Principal issuerX500Principal = signingcert.getIssuerX500Principal();
                logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by "
                        + issuerX500Principal.getName() + ", attempting to retrieve certificate");
                Security.setProperty("ocsp.enable", "false");
                X509Certificate issuer = FindCertByDN(issuerX500Principal);
                if (issuer == null) {
                    OutErrorMessage.set(
                            "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. "
                                    + OutErrorMessage.get());
                    //throw new CertificateException("unable to locate the issuers certificate in the trust store");
                } else {
                    RevocationStatus check = OCSP.check(signingcert, issuer);
                    logger.info("certificate " + signingcert.getSubjectDN().toString()
                            + " revocation status is " + check.getCertStatus().toString() + " reason "
                            + check.getRevocationReason().toString());
                    if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) {
                        OutErrorMessage
                                .set("Certificate status is " + check.getCertStatus().toString() + " reason "
                                        + check.getRevocationReason().toString() + "." + OutErrorMessage.get());

                        //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString());
                    }
                }
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_CRL)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) {
                logger.info("verifying revokation status via CRL for X509 public key "
                        + signingcert.getSubjectDN().toString());

                Security.setProperty("ocsp.enable", "false");
                System.setProperty("com.sun.security.enableCRLDP", "true");

                X509CertSelector targetConstraints = new X509CertSelector();
                targetConstraints.setCertificate(signingcert);
                PKIXParameters params = new PKIXParameters(GetTrustStore());
                params.setRevocationEnabled(true);
                CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                CertPathValidator certPathValidator = CertPathValidator
                        .getInstance(CertPathValidator.getDefaultType());
                CertPathValidatorResult result = certPathValidator.validate(certPath, params);
                try {
                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
                    logger.info("revokation status via CRL PASSED for X509 public key "
                            + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            if (map.containsKey(CHECK_TRUST_CHAIN)
                    && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) {
                logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString());
                try {
                    PKIXParameters params = new PKIXParameters(GetTrustStore());
                    params.setRevocationEnabled(false);
                    CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                    CertPathValidator certPathValidator = CertPathValidator
                            .getInstance(CertPathValidator.getDefaultType());
                    CertPathValidatorResult result = certPathValidator.validate(certPath, params);

                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;

                    TrustAnchor ta = pkixResult.getTrustAnchor();
                    X509Certificate cert = ta.getTrustedCert();

                    logger.info(
                            "trust chain validated X509 public key " + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage);
            if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) {
                //no error message and its cryptographically valid
                return true;
            }
            return false;
        }

        //last chance validation
        logger.info(
                "signature did not have an embedded X509 public key. reverting to user specified certificate");
        //cert wasn't included in the signature, revert to some other means
        KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE));
        URL url = Thread.currentThread().getContextClassLoader()
                .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
        if (url == null) {
            try {
                url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL();
            } catch (Exception x) {
            }
        }
        if (url == null) {
            try {
                url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
            } catch (Exception x) {
            }
        }
        if (url == null) {
            logger.error("");
            OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and"
                    + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get());
            return false;
        }
        KeyStore.PrivateKeyEntry keyEntry = null;

        ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray());

        if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()));
        } else {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray()));
        }

        Certificate origCert = keyEntry.getCertificate();
        if (map.containsKey(CHECK_TIMESTAMPS)) {
            if (origCert.getPublicKey() instanceof X509Certificate) {
                X509Certificate x = (X509Certificate) origCert.getPublicKey();
                x.checkValidity();
            }
        }
        PublicKey validatingKey = origCert.getPublicKey();
        return verifySignature(docElement, validatingKey, OutErrorMessage);
    } catch (Exception e) {
        //throw new RuntimeException(e);
        logger.error("Error caught validating signature", e);
        OutErrorMessage.set(e.getMessage());
        return false;
    }
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Evaluate whether a given certificate chain should be trusted.
 * Uses the CertPath API to validate a given certificate chain.
 *
 * @param certs Certificate chain to validate
 * @param enableRevocation whether to enable CRL verification or not
 * @return true if the certificate chain is valid, false otherwise
 * @throws WSSecurityException//from w  ww .  jav a2  s  . c  o m
 */
public boolean verifyTrust(X509Certificate[] certs, boolean enableRevocation) throws WSSecurityException {
    try {
        // Generate cert path
        List<X509Certificate> certList = Arrays.asList(certs);
        CertPath path = getCertificateFactory().generateCertPath(certList);

        Set<TrustAnchor> set = new HashSet<TrustAnchor>();
        if (truststore != null) {
            Enumeration<String> truststoreAliases = truststore.aliases();
            while (truststoreAliases.hasMoreElements()) {
                String alias = truststoreAliases.nextElement();
                X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                if (cert != null) {
                    TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID));
                    set.add(anchor);
                }
            }
        }

        //
        // Add certificates from the keystore - only if there is no TrustStore, apart from
        // the case that the truststore is the JDK CA certs. This behaviour is preserved
        // for backwards compatibility reasons
        //
        if (keystore != null && (truststore == null || loadCACerts)) {
            Enumeration<String> aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
                if (cert != null) {
                    TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID));
                    set.add(anchor);
                }
            }
        }

        PKIXParameters param = new PKIXParameters(set);
        param.setRevocationEnabled(enableRevocation);
        if (enableRevocation && crlCertStore != null) {
            param.addCertStore(crlCertStore);
        }

        // Verify the trust path using the above settings
        String provider = getCryptoProvider();
        CertPathValidator validator = null;
        if (provider == null || provider.length() == 0) {
            validator = CertPathValidator.getInstance("PKIX");
        } else {
            validator = CertPathValidator.getInstance("PKIX", provider);
        }
        validator.validate(path, param);
        return true;
    } catch (java.security.NoSuchProviderException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.cert.CertificateException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.InvalidAlgorithmParameterException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.cert.CertPathValidatorException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (java.security.KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (NullPointerException e) {
        // NPE thrown by JDK 1.7 for one of the test cases
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    }
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

boolean validateCertificate(Certificate cert) {
    boolean isValidated;

    if (cert == null) {
        return false;
    }// ww  w.j a va2 s .  c  om

    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;
}

From source file:org.josso.auth.scheme.validation.CRLX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {// ww w .ja v  a2s  .  c om
        URL crlUrl = null;
        if (_url != null) {
            crlUrl = new URL(_url);
            log.debug("Using the CRL server at: " + _url);
        } else {
            log.debug("Using the CRL server specified in the certificate.");
            System.setProperty("com.sun.security.enableCRLDP", "true");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // disable OCSP
        Security.setProperty("ocsp.enable", "false");

        // get a certificate revocation list
        if (crlUrl != null) {
            URLConnection connection = crlUrl.openConnection();
            connection.setDoInput(true);
            connection.setUseCaches(false);
            DataInputStream inStream = new DataInputStream(connection.getInputStream());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509CRL crl = (X509CRL) cf.generateCRL(inStream);
            inStream.close();
            params.addCertStore(CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(Collections.singletonList(crl))));
        }

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.josso.auth.scheme.validation.OCSPX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {/* ww w .j av  a 2 s  .  com*/
        if (_url != null) {
            log.debug("Using the OCSP server at: " + _url);
            Security.setProperty("ocsp.responderURL", _url);
        } else {
            log.debug("Using the OCSP server specified in the " + "Authority Info Access (AIA) extension "
                    + "of the certificate");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // init cert store
        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        if (_ocspCert == null) {
            _ocspCert = getCertificate(_ocspResponderCertificateAlias);
        }
        if (_ocspCert != null) {
            certSet.add(_ocspCert);
            CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
            CertStore store = CertStore.getInstance("Collection", storeParams);
            params.addCertStore(store);
            Security.setProperty("ocsp.responderCertSubjectName",
                    _ocspCert.getSubjectX500Principal().getName());
        }

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // activate OCSP
        Security.setProperty("ocsp.enable", "true");

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.texai.x509.X509Utils.java

/** Validates the given X.509 certificate path, throwing an exception if the path is invalid.
 *
 * @param certPath the given X.509 certificate path, which does not include the trust anchor in contrast to a
 * certificate chain that does/*w  w  w.j  a v  a  2s  . c  o  m*/
 *
 * @throws InvalidAlgorithmParameterException if an invalid certificate path validation parameter is provided
 * @throws NoSuchAlgorithmException if an invalid encryption algorithm is specified
 * @throws CertPathValidatorException if the given x.509 certificate path is invalid
 */
public static void validateCertificatePath(final CertPath certPath)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertPathValidatorException {
    //Preconditions
    assert certPath != null : "certPath must not be null";

    final Set<TrustAnchor> trustAnchors = new HashSet<>();
    trustAnchors.add(new TrustAnchor(X509Utils.getRootX509Certificate(), null)); // nameConstraints
    final PKIXParameters params = new PKIXParameters(trustAnchors);
    params.setSigProvider(BOUNCY_CASTLE_PROVIDER);
    params.setRevocationEnabled(false);
    final CertPathValidator certPathValidator = CertPathValidator
            .getInstance(CertPathValidator.getDefaultType());
    certPathValidator.validate(certPath, params);
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {

    try {/*from w  w w  .ja va 2 s  .c  o m*/

        // 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;
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

private boolean validateCertPath(KeyStore ks, Certificate[] certs) throws WSSecurityException {

    try {/*w  w w.  j a v  a 2  s .c om*/

        // Generate cert path
        List certList = 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 ex) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { ex.getMessage() },
                ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { ex.getMessage() },
                ex);
    } catch (CertificateException ex) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { ex.getMessage() },
                ex);
    } catch (InvalidAlgorithmParameterException ex) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { ex.getMessage() },
                ex);
    } catch (CertPathValidatorException ex) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { ex.getMessage() },
                ex);
    } catch (KeyStoreException ex) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { ex.getMessage() },
                ex);
    }

    return true;
}