Example usage for java.security.cert TrustAnchor getTrustedCert

List of usage examples for java.security.cert TrustAnchor getTrustedCert

Introduction

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

Prototype

public final X509Certificate getTrustedCert() 

Source Link

Document

Returns the most-trusted CA certificate.

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);/* w w w . j av a  2  s. c  om*/

    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);// w ww.  j a v  a2 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:CAList.java

/**
 * <p><!-- Method description --></p>
 *
 *
 * @param args//  w  ww  . ja va 2  s.  c  o  m
 */
public static void main(String[] args) {
    try {
        // Load the JDK's cacerts keystore file
        String filename = System.getProperty("java.home")
                + "/lib/security/cacerts".replace('/', File.separatorChar);
        FileInputStream is = new FileInputStream(filename);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "changeit";
        keystore.load(is, password.toCharArray());

        // This class retrieves the most-trusted CAs from the keystore
        PKIXParameters params = new PKIXParameters(keystore);

        // Get the set of trust anchors, which contain the most-trusted CA certificates
        Iterator it = params.getTrustAnchors().iterator();
        for (; it.hasNext();) {
            TrustAnchor ta = (TrustAnchor) it.next();

            // Get certificate
            X509Certificate cert = ta.getTrustedCert();
            System.out.println("<issuer>" + cert.getIssuerDN() + "</issuer>\n");
        }
    } catch (CertificateException e) {
    } catch (KeyStoreException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidAlgorithmParameterException e) {
    } catch (IOException e) {
    }
}

From source file:mitm.application.djigzo.ws.impl.CertificateValidatorWSImpl.java

@Override
@StartTransaction//from  ww w.  ja va2  s . c om
public X509CertificateDTO getIssuerCertificate(CertificateStore store, String thumbprint)
        throws WebServiceCheckedException {
    X509Certificate certificate = getCertificate(store, thumbprint);

    if (certificate == null) {
        throw new WebServiceCheckedException("Certificate not found");
    }

    X509CertificateDTO issuerDTO = null;

    try {
        CertificatePathBuilder pathBuilder = pKISecurityServices.getCertificatePathBuilderFactory()
                .createCertificatePathBuilder();

        CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate);

        CertPath certPath = pathBuilderResult.getCertPath();

        if (certPath != null) {
            X509Certificate issuer = null;
            CertificateStore issuerStore = null;

            List<? extends Certificate> path = certPath.getCertificates();

            if (CollectionUtils.isNotEmpty(path)) {
                if (CollectionUtils.getSize(path) == 1) {
                    /*
                     * Since there is only one certificate (the certificate itself) we need
                     * to check whether there is a root in the path
                     */
                    if (pathBuilderResult instanceof PKIXCertPathBuilderResult) {
                        TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult)
                                .getTrustAnchor();

                        if (trustAnchor != null) {
                            issuer = trustAnchor.getTrustedCert();

                            issuerStore = CertificateStore.ROOTS;
                        }
                    }
                } else {
                    issuer = (X509Certificate) path.get(1);

                    issuerStore = CertificateStore.CERTIFICATES;
                }
            }

            if (issuer != null) {
                issuerDTO = certificateDTOBuilder.buildCertificateDTO(issuer, null);
                issuerDTO.setCertificateStore(issuerStore);
            }
        }
    } catch (CertPathBuilderException e) {
        /*
         * Log on debug level because CertPathBuilderException is for example thrown
         * when trying to get the issuer of a root for example
         */
        logger.debug("getIssuer failed.", e);
    }

    return issuerDTO;
}

From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java

private void getPFXTransacted(Collection<X509Certificate> certificates, char[] password, boolean includeRoot,
        OutputStream pfx) throws KeyStoreException {
    try {/*from ww w.j a  v  a 2  s  .  co m*/
        KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

        keyStore.load(null);

        for (X509Certificate certificate : certificates) {
            if (certificate == null) {
                continue;
            }

            X509CertStoreEntry entry = keyAndCertStore.getByCertificate(certificate);

            if (entry != null && entry.getCertificate() != null) {
                KeyAndCertificate keyAndCertificate = keyAndCertStore.getKeyAndCertificate(entry);

                if (keyAndCertificate != null) {
                    if (!certificate.equals(keyAndCertificate.getCertificate())) {
                        throw new IllegalStateException("Certificate mismatch.");
                    }

                    X509Certificate[] chain = null;

                    /*
                     * Build a certificate chain so we add the chain (if valid)
                     */
                    try {
                        CertificatePathBuilder pathBuilder = pathBuilderFactory.createCertificatePathBuilder();

                        CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(certificate);

                        X509Certificate root = null;

                        if (includeRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) {
                            TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult)
                                    .getTrustAnchor();

                            if (trustAnchor != null) {
                                root = trustAnchor.getTrustedCert();
                            }
                        }

                        CertPath certPath = pathBuilderResult.getCertPath();

                        if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) {
                            List<X509Certificate> completePath = new LinkedList<X509Certificate>();

                            for (Certificate fromPath : certPath.getCertificates()) {
                                if (!(fromPath instanceof X509Certificate)) {
                                    /*
                                     * only X509Certificates are supported
                                     */
                                    continue;
                                }

                                completePath.add((X509Certificate) fromPath);
                            }

                            if (root != null && includeRoot) {
                                completePath.add(root);
                            }

                            chain = new X509Certificate[completePath.size()];

                            chain = completePath.toArray(chain);
                        }
                    } catch (CertPathBuilderException e) {
                        logger.warn(
                                "Could not build a path. Message: " + ExceptionUtils.getRootCauseMessage(e));
                    }

                    if (ArrayUtils.getLength(chain) == 0) {
                        chain = new X509Certificate[] { certificate };
                    }

                    String alias = X509CertificateInspector.getThumbprint(certificate);

                    if (keyAndCertificate.getPrivateKey() != null) {
                        keyStore.setKeyEntry(alias, keyAndCertificate.getPrivateKey(), password, chain);
                    } else {
                        keyStore.setCertificateEntry(alias, certificate);
                    }
                }
            }
        }

        keyStore.store(pfx, password);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e);
    } catch (IOException e) {
        throw new KeyStoreException(e);
    } catch (CertStoreException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchProviderException e) {
        throw new NoSuchProviderRuntimeException(e);
    } catch (SecurityFactoryFactoryException e) {
        throw new KeyStoreException(e);
    }
}

From source file:org.globus.security.stores.PEMKeyStore.java

private void loadDirectories(String directoryList) throws CertificateException {

    try {// w  w  w. j av  a2s .  c o m
        caDelegate.loadWrappers(directoryList);
        Map<String, ResourceTrustAnchor> wrapperMap = caDelegate.getWrapperMap();
        for (ResourceTrustAnchor trustAnchor : wrapperMap.values()) {
            String alias = trustAnchor.getResourceURL().toExternalForm();
            TrustAnchor tmpTrustAnchor = trustAnchor.getTrustAnchor();
            X509Certificate trustCert = tmpTrustAnchor.getTrustedCert();
            certFilenameMap.put(trustCert, alias);
            if (this.aliasObjectMap == null) {
                System.out.println("Alias Map Null");
            }
            this.aliasObjectMap.put(alias, trustAnchor);
        }
    } catch (ResourceStoreException e) {
        throw new CertificateException(e);
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMESign.java

private X509Certificate[] getCertificateChain(X509Certificate signingCertificate) {
    X509Certificate[] chain = null;

    try {//  www  .j  a  v  a  2s .co m
        /*
         * Use CertificatePathBuilderFactory instead of PKITrustCheckCertificateValidator because we
         * assume that the signing certificate was already checked for revocation etc. 
         * CertificatePathBuilderFactory is faster than PKITrustCheckCertificateValidator
         */
        CertificatePathBuilder pathBuilder = certificatePathBuilderFactory.createCertificatePathBuilder();

        CertPathBuilderResult pathBuilderResult = pathBuilder.buildPath(signingCertificate);

        CertPath certPath = pathBuilderResult.getCertPath();

        if (certPath != null && CollectionUtils.isNotEmpty(certPath.getCertificates())) {
            X509Certificate root = null;

            if (addRoot && pathBuilderResult instanceof PKIXCertPathBuilderResult) {
                TrustAnchor trustAnchor = ((PKIXCertPathBuilderResult) pathBuilderResult).getTrustAnchor();

                if (trustAnchor != null) {
                    root = trustAnchor.getTrustedCert();
                }
            }

            List<X509Certificate> completePath = new LinkedList<X509Certificate>();

            for (Certificate fromPath : certPath.getCertificates()) {
                if (!(fromPath instanceof X509Certificate)) {
                    /*
                     * only X509Certificates are supported
                     */
                    continue;
                }

                completePath.add((X509Certificate) fromPath);
            }

            if (root != null && addRoot) {
                completePath.add(root);
            }

            chain = new X509Certificate[completePath.size()];

            chain = completePath.toArray(chain);
        }
    } catch (CertPathBuilderException e) {
        if (getLogger().isDebugEnabled()) {
            getLogger().warn("Error building path for signing certificate.", e);
        } else {
            getLogger().warn(
                    "Error building path for signing certificate. " + ExceptionUtils.getRootCauseMessage(e));
        }
    }

    if (chain == null) {
        chain = new X509Certificate[] { signingCertificate };
    }

    return chain;
}

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  ww. j  a  v a  2  s.c  o m

    return alTrustedCertificates;
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

@Override
public RevocationResult getRevocationStatus(CertPath certPath, TrustAnchor trustAnchor, Date now)
        throws CRLException {
    Check.notNull(certPath, "certPath");
    Check.notNull(trustAnchor, "trustAnchor");

    List<? extends Certificate> certificates = certPath.getCertificates();

    RevocationResult revocationResult = new RevocationResultImpl(certificates.size());

    /* /* w w w  .ja  va  2  s  . co m*/
     * Step through all the certificates in the path and check the revocation status of all
     * the certificates in the path.
     */
    for (int i = 0; i < certificates.size(); i++) {
        X509Certificate certificate = toX509Certificate(certificates.get(i));

        PublicKey issuerPublicKey;
        X500Principal issuer;
        X509Certificate issuerCertificate;

        /*
         * we need to get the issuer of the current certificate
         * check if there is a next certificate in the path or that we must use the TrustAnchor
         */
        if ((i + 1) == certificates.size()) {
            /* this was the last entry from the path so we must use the trust anchor */
            if (trustAnchor.getTrustedCert() != null) {
                issuerCertificate = toX509Certificate(trustAnchor.getTrustedCert());
                issuerPublicKey = issuerCertificate.getPublicKey();
                issuer = issuerCertificate.getSubjectX500Principal();
            } else {
                /* the TrustAnchor does not contain a certificate but only an issuer and public key */
                issuerCertificate = null;
                issuerPublicKey = trustAnchor.getCAPublicKey();
                issuer = trustAnchor.getCA();
            }
        } else {
            /* get next entry from path ie. the issuer of the current certificate */
            issuerCertificate = toX509Certificate(certificates.get(i + 1));
            issuerPublicKey = issuerCertificate.getPublicKey();
            issuer = issuerCertificate.getSubjectX500Principal();
        }

        /*
         * sanity check to make sure the CertPath is ordered from end -> final CA
         * ie that the next certificate signed the previous certificate
         */
        verifyCertificate(certificate, issuerPublicKey);

        /* 
         * Sanity check. The issuer principal field of the certificate currently checked should 
         * normally be equal to the issuer principal.
         */
        if (!certificate.getIssuerX500Principal().equals(issuer)) {
            logger.warn("Certificate issuer field is not equal to issuer.");
        }

        if (issuerCertificate != null) {
            Set<KeyUsageType> keyUsage = X509CertificateInspector.getKeyUsage(issuerCertificate);

            /* 
             * check if issuer is allowed to issue CRLs (only when we have an issuerCertificate, and
             * a key usage extension) 
             */
            if (keyUsage != null && !keyUsage.contains(KeyUsageType.CRLSIGN)) {
                logger.debug("Issuer is not allowed to issue CRLs.");

                /*
                 * We will return UNKNOWN status.
                 */
                RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

                revocationResult.getDetails()[i] = detail;

                /* there is no need to continue because issuer is not allowed to issue CRLs */
                break;
            }
        }

        X509CRLSelector crlSelector = new X509CRLSelector();

        /* create a selector to find all relevant CRLs that were issued to the same issuer as the certificate */
        crlSelector.addIssuer(issuer);

        try {
            List<X509CRL> crls = findCRLs(certificate, crlSelector, issuerPublicKey, now);

            RevocationDetail detail = getRevocationDetail(crls, certificate, issuerCertificate, issuerPublicKey,
                    now);

            revocationResult.getDetails()[i] = detail;

            if (detail.getStatus() == RevocationStatus.REVOKED) {
                logger.warn("Certificate is revoked.");

                if (logger.isDebugEnabled()) {
                    logger.debug("Revoked certificate: " + certificate);
                }

                /* there is no need to continue because the CRL is revoked */
                break;
            }
        } catch (NoSuchProviderException e) {
            throw new NoSuchProviderRuntimeException(e);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Revocation status for CertPath " + certPath + " and TrustAnchor " + trustAnchor + " is "
                + revocationResult);
    }

    return revocationResult;
}

From source file:mitm.common.security.crl.PKITSTest.java

@Test
public void test_4_7_4_Invalid_keyUsage_Critical_cRLSign_False_Test4() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/keyUsageCriticalcRLSignFalseCACert.crt"),
            certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/InvalidkeyUsageCriticalcRLSignFalseTest4EE.crt"),
            certStoreParams.getCertStore());

    // add crls//from w  ww  .  j a  v a 2 s  . c o m
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/keyUsageCriticalcRLSignFalseCACRL.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("1"));
    selector.setIssuer("CN=keyUsage Critical cRLSign False CA, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);
    assertEquals("CN=Trust Anchor, O=Test Certificates, C=US",
            trustAnchor.getTrustedCert().getSubjectX500Principal().toString());

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, testDate);

    assertEquals(RevocationStatus.UNKNOWN, revocationResult.getStatus());
}