Example usage for java.security.cert PKIXParameters PKIXParameters

List of usage examples for java.security.cert PKIXParameters PKIXParameters

Introduction

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

Prototype

public PKIXParameters(KeyStore keystore) throws KeyStoreException, InvalidAlgorithmParameterException 

Source Link

Document

Creates an instance of PKIXParameters that populates the set of most-trusted CAs from the trusted certificate entries contained in the specified KeyStore .

Usage

From source file:com.verisign.epp.serverstub.LaunchDomainHandler.java

/**
 * Loads the trust store file and the Certificate Revocation List (CRL) file
 * into the <code>PKIXParameters</code> used to verify the certificate chain
 * and verify the certificate against the CRL. Both the Java Trust Store is
 * loaded with the trusted root CA certificates (trust anchors) and the CRL
 * file is attempted to be loaded to identify the revoked certificates. If
 * the CRL file is not found, then no CRL checking will be done.
 * /*w w  w . j a va  2 s.  co  m*/
 * @param aTrustStoreName
 *            Trust store file name
 * @param aCrls
 *            List of Certificate Revocation List (CRL) file names
 * 
 * @return Initialized <code>PKIXParameters</code> instance.
 * 
 * @throws Exception
 *             Error initializing the PKIX parameters
 */
private PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception {
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): enter");

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);
    trustStoreFile.close();
    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): truststore = " + aTrustStoreName);
    PKIXParameters pkixParameters = new PKIXParameters(trustStore);

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

    Collection crlContentsList = new ArrayList();

    for (String currCrl : aCrls) {
        File crlFile = new File(currCrl);
        if (crlFile.exists()) {
            InputStream inStream = null;

            try {
                cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): adding CRL " + currCrl);
                inStream = new FileInputStream(currCrl);
                crlContentsList.add(certFactory.generateCRL(inStream));
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            throw new EPPException("CRL file " + currCrl + " does not exist.");
        }

    }

    // At least 1 CRL was loaded
    if (crlContentsList.size() != 0) {

        List<CertStore> certStores = new ArrayList<CertStore>();
        certStores.add(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlContentsList)));

        pkixParameters.setCertStores(certStores);
        pkixParameters.setRevocationEnabled(true);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation enabled");
    } else {
        pkixParameters.setRevocationEnabled(false);
        cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): Revocation disabled");
    }

    cat.debug("LaunchDomainHandler.loadPKIXParameters(String, String): exit");
    return pkixParameters;
}

From source file:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java

/**
 * Validate a given certificate chain./*from   w w  w.  j a  v  a2s . co m*/
 * @see Crypto#validateCertPath(java.security.cert.X509Certificate[])
 */
public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException {
    boolean ok = false;
    try {
        // Generate cert path
        List<X509Certificate> certList = Arrays.asList(certs);
        CertPath path = this.getCertificateFactory().generateCertPath(certList);

        HashSet<TrustAnchor> set = new HashSet<TrustAnchor>();

        if (certs.length == 1) // Use factory certs
        {
            String alias = _factory.getAliasForX509Cert(certs[0].getIssuerDN().getName(),
                    certs[0].getSerialNumber());
            if (alias == null) {
                _logger.debug("Certificate not trusted");
                return false;
            }

            X509Certificate cert = (X509Certificate) _factory.getCertificate(alias);
            TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30"));
            set.add(anchor);
        } else {
            // Add certificates from the keystore
            Enumeration aliases = _factory.getAliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                X509Certificate cert = (X509Certificate) _factory.getCertificate(alias);
                TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30"));
                set.add(anchor);
            }
        }

        PKIXParameters param = new PKIXParameters(set);
        param.setRevocationEnabled(false);
        Provider provider = _factory.getKeyStore().getProvider();
        String sProvider = null;
        CertPathValidator certPathValidator = null;
        if (provider != null) {
            sProvider = provider.getName();
        }
        if (sProvider == null || sProvider.length() == 0) {
            certPathValidator = CertPathValidator.getInstance("PKIX");
        } else {
            certPathValidator = CertPathValidator.getInstance("PKIX", sProvider);
        }
        certPathValidator.validate(path, param);
        ok = true;
    } catch (NoSuchProviderException e) {
        _logger.warn("No such provider", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (NoSuchAlgorithmException e) {
        _logger.warn("No such algorithm", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (InvalidAlgorithmParameterException e) {
        _logger.warn("Invalid algorithm param", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CertificateException e) {
        _logger.warn("Invalid certificate", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (ClassCastException e) {
        _logger.warn("Certificate is not an X509Certificate", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CertPathValidatorException e) {
        _logger.warn("Could not validate Cert Path", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CryptoException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    }
    return ok;
}

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  .  ja  va2 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:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Create parameters for CertPathValidator using PKIX algorithm.
 *
 * The parameter object was defined with given trustStore and CRL collection
 * @param trustStore2/*from   w  ww  .  j av a 2  s. c om*/
 * @return non-null PKIXParameters
 * @throws CertificateRevocationCheckException
 */
private PKIXParameters createPKIXParameters(Collection<Object> crlCollection)
        throws CertificateRevocationCheckException {

    PKIXParameters params = null;
    try {
        Validate.notNull(trustStore, "TrustStore can not be null.");
        params = new PKIXParameters(trustStore);

        if (this.certPolicy.revocationCheckEnabled()) {
            params.setRevocationEnabled(true);
        } else {
            params.setRevocationEnabled(false);
        }
    } catch (KeyStoreException e) {
        throw new CertificateRevocationCheckException(
                "Error creating validator parameters: Please check trust store" + e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateRevocationCheckException("Error creating validator parameters:" + e.getMessage(),
                e);
    } catch (Throwable e) {
        //have this block in case a new type of error was thrown
        throw new CertificateRevocationCheckException("Error creating validator parameters:" + e.getMessage(),
                e);
    }

    if (!crlCollection.isEmpty()) {
        try {
            CertStore crlStore = CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(crlCollection));
            params.addCertStore(crlStore);
        } catch (InvalidAlgorithmParameterException e) {
            throw new CertificateRevocationCheckException(
                    "Error adding CRLs to validating parameters:" + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new CertificateRevocationCheckException(
                    "Error adding CRLs to validating parameters:" + e.getMessage(), e);
        }
    } else {
        logger.debug("Revocation check: CRL list empty");
    }

    // setup certificate policy white list

    String[] oidWhiteList = this.certPolicy.getOIDs();

    if (oidWhiteList != null && oidWhiteList.length > 0) {
        Set<String> oidSet = new HashSet<String>();
        for (String oid : oidWhiteList) {
            oidSet.add(oid);
        }
        params.setInitialPolicies(oidSet);
        params.setExplicitPolicyRequired(true);
    }
    return params;

}

From source file:controller.CCInstance.java

public ArrayList<Certificate> getTrustedCertificatesFromKeystore(KeyStore keystore) throws KeyStoreException,
        IOException, NoSuchAlgorithmException, CertificateException, InvalidAlgorithmParameterException {

    final PKIXParameters params = new PKIXParameters(keystore);
    final ArrayList<Certificate> alTrustedCertificates = new ArrayList<>();

    for (final TrustAnchor ta : params.getTrustAnchors()) {
        Certificate cert = (Certificate) ta.getTrustedCert();
        alTrustedCertificates.add(cert);
    }// w w w .  j a  va2  s .  co m

    return alTrustedCertificates;
}

From source file:com.verisign.epp.codec.verificationcode.EPPVerificationCodeTst.java

/**
 * Loads the trust store file into the <code>PKIXParameters</code> used to
 * verify the certificate chain The Java Trust Store is loaded with the
 * trusted VSP certificates.//from   w ww .  jav a2  s.c o  m
 * 
 * @param aTrustStoreName
 *            Trust store file name
 * 
 * @return Initialized <code>PKIXParameters</code> instance.
 * 
 * @throws Exception
 *             Error initializing the PKIX parameters
 */
public static PKIXParameters loadPKIXParameters(String aTrustStoreName) throws Exception {

    trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);

    PKIXParameters pkixParameters = new PKIXParameters(trustStore);
    pkixParameters.setRevocationEnabled(false);

    // Initialize the verification code validator
    verificationCodeValidator = new TrustAnchorVerificationCodeValidator(trustStore);

    return pkixParameters;
}

From source file:com.verisign.epp.codec.launch.EPPLaunchTst.java

/**
 * Loads the trust store file and the Certificate Revocation List (CRL) file
 * into the <code>PKIXParameters</code> used to verify the certificate chain
 * and verify the certificate against the CRL. Both the Java Trust Store is
 * loaded with the trusted root CA certificates (trust anchors) and the CRL
 * file is attempted to be loaded to identify the revoked certificates. If
 * the CRL file is not found, then no CRL checking will be done.
 * /*from   w  w  w . j  av a 2s .  co m*/
 * @param aTrustStoreName
 *            Trust store file name
 * @param aCrls
 *            List of Certificate Revocation List (CRL) file names
 * 
 * @return Initialized <code>PKIXParameters</code> instance.
 * 
 * @throws Exception
 *             Error initializing the PKIX parameters
 */
public static PKIXParameters loadPKIXParameters(String aTrustStoreName, List<String> aCrls) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream trustStoreFile = new FileInputStream(aTrustStoreName);
    trustStore.load(trustStoreFile, null);
    PKIXParameters pkixParameters = new PKIXParameters(trustStore);

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

    Collection crlContentsList = new ArrayList();

    for (String currCrl : aCrls) {
        File crlFile = new File(currCrl);
        if (crlFile.exists()) {
            InputStream inStream = null;

            try {
                inStream = new FileInputStream(currCrl);
                crlContentsList.add(certFactory.generateCRL(inStream));
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            System.err.println("CRL file \"" + currCrl + "\" NOT found.");
        }

    }

    // At least 1 CRL was loaded
    if (crlContentsList.size() != 0) {

        List<CertStore> certStores = new ArrayList<CertStore>();
        certStores.add(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlContentsList)));

        pkixParameters.setCertStores(certStores);
        pkixParameters.setRevocationEnabled(true);
        System.out.println("Revocation enabled");
    } else {
        pkixParameters.setRevocationEnabled(false);
        System.out.println("Revocation disabled.");

    }

    return pkixParameters;
}

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>//from   w ww.  ja  va 2s  . c  om
 * 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.synapse.transport.certificatevalidation.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/*from w w  w  . j ava  2 s.  c o  m*/
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

        // perform validation
        CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.info("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on certificate number "
                + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}

From source file:org.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/*from w  w w .j a  v  a  2 s  .co  m*/
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

        // perform validation
        CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.debug("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on "
                + "certificate number " + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}