Example usage for java.security.cert PKIXCertPathValidatorResult getTrustAnchor

List of usage examples for java.security.cert PKIXCertPathValidatorResult getTrustAnchor

Introduction

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

Prototype

public TrustAnchor getTrustAnchor() 

Source Link

Document

Returns the TrustAnchor describing the CA that served as a trust anchor for the certification path.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String filename = System.getProperty("java.home")
            + "/lib/security/cacerts".replace('/', File.separatorChar);
    FileInputStream is = new FileInputStream(filename);
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    String password = "password";
    keystore.load(is, password.toCharArray());

    PKIXParameters params = new PKIXParameters(keystore);

    params.setRevocationEnabled(false);//from  w w  w . j a  va 2 s  .c o  m

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

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

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    List mylist = new ArrayList();

    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);//from w  w  w  .  java2 s . c  o m

    CertPath cp = cf.generateCertPath(mylist);

    FileInputStream kin = new FileInputStream(args[0]);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(kin, args[1].toCharArray());

    PKIXParameters params = new PKIXParameters(ks);
    params.setRevocationEnabled(false);

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);

    PublicKey pbk = result.getPublicKey();
    byte[] pkenc = pbk.getEncoded();
    BigInteger pk = new BigInteger(pkenc);
    System.out.println(pk.toString(16));

    TrustAnchor anc = result.getTrustAnchor();
    X509Certificate xc = anc.getTrustedCert();
    System.out.println(xc.getSubjectDN());
    System.out.println(xc.getIssuerDN());

}

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 va  2s. 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.cesecore.util.CertTools.java

/**
 * Method to create certificate path and to check it's validity from a list of certificates. The list of certificates should only contain one root
 * certificate./*from  w  ww.j  a  v a  2  s .  c  o  m*/
 * 
 * @param certlist
 * @return the certificatepath with the root CA at the end
 * @throws CertPathValidatorException if the certificate chain can not be constructed
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
public static List<Certificate> createCertChain(Collection<?> certlistin)
        throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateException {
    final List<Certificate> returnval = new ArrayList<Certificate>();

    Collection<Certificate> certlist = orderCertificateChain(certlistin);

    // set certificate chain
    Certificate rootcert = null;
    ArrayList<Certificate> calist = new ArrayList<Certificate>();
    for (Certificate next : certlist) {
        if (CertTools.isSelfSigned(next)) {
            rootcert = next;
        } else {
            calist.add(next);
        }
    }

    if (calist.isEmpty()) {
        // only one root cert, no certchain
        returnval.add(rootcert);
    } else {
        // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator
        Certificate test = calist.get(0);
        if (test.getType().equals("CVC")) {
            if (calist.size() == 1) {
                returnval.add(test);
                returnval.add(rootcert);
            } else {
                throw new CertPathValidatorException(
                        "CVC certificate chain can not be of length longer than two.");
            }
        } else {
            // Normal X509 certificates
            HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>();
            TrustAnchor trustanchor = null;
            trustanchor = new TrustAnchor((X509Certificate) rootcert, null);
            trustancors.add(trustanchor);

            // Create the parameters for the validator
            PKIXParameters params = new PKIXParameters(trustancors);

            // Disable CRL checking since we are not supplying any CRLs
            params.setRevocationEnabled(false);
            params.setDate(new Date());

            // Create the validator and validate the path
            CertPathValidator certPathValidator = CertPathValidator
                    .getInstance(CertPathValidator.getDefaultType(), "BC");
            CertificateFactory fact = CertTools.getCertificateFactory();
            CertPath certpath = fact.generateCertPath(calist);

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

            // Get the certificates validate in the path
            PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
            returnval.addAll(certpath.getCertificates());

            // Get the CA used to validate this path
            TrustAnchor ta = pkixResult.getTrustAnchor();
            X509Certificate cert = ta.getTrustedCert();
            returnval.add(cert);
        }
    }
    return returnval;
}

From source file:org.ejbca.util.CertTools.java

/**
 * Method to create certificate path and to check it's validity from a list of certificates.
 * The list of certificates should only contain one root certificate.
 *
 * @param certlist//from  w ww .j a va2s.  c om
 * @return the certificatepath with the root CA at the end, either collection of Certificate or byte[] (der encoded certs)
 * @throws CertPathValidatorException if the certificate chain can not be constructed
 * @throws InvalidAlgorithmParameterException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws CertificateException 
 */
public static Collection<Certificate> createCertChain(Collection<?> certlistin)
        throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateException {
    ArrayList<Certificate> returnval = new ArrayList<Certificate>();

    Collection<Certificate> certlist = orderCertificateChain(certlistin);

    // set certificate chain
    Certificate rootcert = null;
    ArrayList<Certificate> calist = new ArrayList<Certificate>();
    Iterator<Certificate> iter = certlist.iterator();
    while (iter.hasNext()) {
        Certificate next = iter.next();
        if (CertTools.isSelfSigned(next)) {
            rootcert = next;
        } else {
            calist.add(next);
        }
    }

    if (calist.isEmpty()) {
        // only one root cert, no certchain
        returnval.add(rootcert);
    } else {
        // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator
        Certificate test = calist.get(0);
        if (test.getType().equals("CVC")) {
            if (calist.size() == 1) {
                returnval.add(test);
                returnval.add(rootcert);
            } else {
                throw new CertPathValidatorException(
                        "CVC certificate chain can not be of length longer than two.");
            }
        } else {
            // Normal X509 certificates
            HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>();
            TrustAnchor trustanchor = null;
            trustanchor = new TrustAnchor((X509Certificate) rootcert, null);
            trustancors.add(trustanchor);

            // Create the parameters for the validator
            PKIXParameters params = new PKIXParameters(trustancors);

            // Disable CRL checking since we are not supplying any CRLs
            params.setRevocationEnabled(false);
            params.setDate(new Date());

            // Create the validator and validate the path
            CertPathValidator certPathValidator = CertPathValidator
                    .getInstance(CertPathValidator.getDefaultType(), "BC");
            CertificateFactory fact = CertTools.getCertificateFactory();
            CertPath certpath = fact.generateCertPath(calist);

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

            // Get the certificates validate in the path
            PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
            returnval.addAll(certpath.getCertificates());

            // Get the CA used to validate this path
            TrustAnchor ta = pkixResult.getTrustAnchor();
            X509Certificate cert = ta.getTrustedCert();
            returnval.add(cert);
        }
    }
    return returnval;
}

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

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {// w ww .j ava  2  s  .c  o  m
        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 {//from   w  w w  . j a  va 2 s  . co  m
        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");
}