Example usage for java.security.cert CertificateException CertificateException

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

Introduction

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

Prototype

public CertificateException(String message, Throwable cause) 

Source Link

Document

Creates a CertificateException with the specified detail message and cause.

Usage

From source file:org.apache.directory.studio.connection.core.io.StudioTrustManager.java

private X509TrustManager getTrustManager(KeyStore trustStore) throws CertificateException {
    try {/*from ww w. j  a  v  a2 s  .co  m*/
        Enumeration<String> aliases = trustStore.aliases();
        if (aliases.hasMoreElements()) {
            TrustManagerFactory factory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init(trustStore);
            TrustManager[] permanentTrustManagers = factory.getTrustManagers();
            TrustManager permanentTrustManager = permanentTrustManagers[0];
            return (X509TrustManager) permanentTrustManager;
        }
    } catch (Exception e) {
        throw new CertificateException(Messages.StudioTrustManager_CantCreateTrustManager, e);
    }

    return null;
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private X509Certificate generateCertificate(X500Principal subject, PublicKey subjectPublic,
        X500Principal issuer, PublicKey issuerPublicKey, PrivateKey issuerPrivateKey, boolean isCaCert)
        throws CertificateException {
    try {/*from w  ww.j  a  v a2  s  .co m*/
        final Date notBefore = new Date();
        final Date notAfter = new Date(notBefore.getTime() + DEFAULT_VALIDITY);
        final X500Signer signer = createCertificateSigner(issuer, issuerPrivateKey);
        final CertificateValidity validity = new CertificateValidity(notBefore, notAfter);
        final X509CertInfo info = createCertificateInfo(subject, subjectPublic, issuer, issuerPublicKey,
                validity, signer);
        final CertificateExtensions extensions = (isCaCert) ? (getCACertificateExtensions())
                : (getCertificateExtensions(subjectPublic, issuerPublicKey));
        info.set(X509CertInfo.EXTENSIONS, extensions);
        final X509CertImpl cert = new X509CertImpl(info);
        cert.sign(issuerPrivateKey, SIGNATURE_ALGORITHM);
        return cert;
    } catch (Exception e) {
        throw new CertificateException("Failed to generate certificate: " + e.getMessage(), e);
    }
}

From source file:org.opensaml.xml.security.x509.X509Util.java

/**
 * Decodes X.509 certificates in DER or PEM format.
 * /* www .  j  a  v  a 2s .c o  m*/
 * @param certs encoded certs
 * 
 * @return decoded certs
 * 
 * @throws CertificateException thrown if the certificates can not be decoded
 */
@SuppressWarnings("unchecked")
public static Collection<X509Certificate> decodeCertificate(byte[] certs) throws CertificateException {
    try {
        TrustMaterial tm = new TrustMaterial(certs);
        return tm.getCertificates();
    } catch (Exception e) {
        throw new CertificateException("Unable to decode X.509 certificates", e);
    }
}

From source file:org.apache.directory.studio.connection.core.StudioKeyStoreManager.java

/**
 * Removes the certificate from the file key store.
 * //from   w  ww. j  a  v a 2s .c o m
 * @param certificate the certificate
 */
private void removeFromFileKeyStore(X509Certificate certificate) throws CertificateException {
    try {
        KeyStore fileKeyStore = getFileKeyStore();
        removeFromKeyStore(certificate, fileKeyStore);
        File file = ConnectionCorePlugin.getDefault().getStateLocation().append(filename).toFile();
        fileKeyStore.store(new FileOutputStream(file), password.toCharArray());
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateException(Messages.StudioKeyStoreManager_CantRemoveCertificateFromTrustStore, e);
    }
}

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

private void loadDirectories(String directoryList) throws CertificateException {

    try {//from  ww  w. j a v a 2s. co  m
        caDelegate.loadWrappers(directoryList);
        Map<String, ResourceTrustAnchor> wrapperMap = caDelegate.getWrapperMap();
        Set<String> knownCerts = new HashSet<String>();
        // The alias hashing merits explanation.  Loading all the files in a directory triggers a
        // deadlock bug for old jglobus clients if the directory contains repeated CAs (like the
        // modern IGTF bundle does).  So, we ignore the cert if the alias is incorrect or already seen.
        // However, we track all the certs we ignore and load any that were completely ignored due to
        // aliases.  So, non-hashed directories will still work.
        Map<String, String> ignoredAlias = new HashMap<String, String>();
        Map<String, ResourceTrustAnchor> ignoredAnchor = new HashMap<String, ResourceTrustAnchor>();
        Map<String, X509Certificate> ignoredCert = new HashMap<String, X509Certificate>();
        for (ResourceTrustAnchor trustAnchor : wrapperMap.values()) {
            String alias = trustAnchor.getResourceURL().toExternalForm();
            TrustAnchor tmpTrustAnchor = trustAnchor.getTrustAnchor();
            X509Certificate trustCert = tmpTrustAnchor.getTrustedCert();
            String hash = CertificateIOUtil.nameHash(trustCert.getSubjectX500Principal());
            if (this.aliasObjectMap == null) {
                System.out.println("Alias Map Null");
            }
            boolean hash_in_alias = !alias.contains(hash);
            if (knownCerts.contains(hash) || !hash_in_alias) {
                if (!hash_in_alias) {
                    ignoredAlias.put(hash, alias);
                    ignoredAnchor.put(hash, trustAnchor);
                    ignoredCert.put(hash, trustCert);
                }
                continue;
            }
            knownCerts.add(hash);
            this.aliasObjectMap.put(alias, trustAnchor);
            certFilenameMap.put(trustCert, alias);
        }
        // Add any CA we skipped above.
        for (String hash : ignoredAlias.keySet()) {
            if (knownCerts.contains(hash)) {
                continue;
            }
            String alias = ignoredAlias.get(hash);
            this.aliasObjectMap.put(alias, ignoredAnchor.get(hash));
            certFilenameMap.put(ignoredCert.get(hash), alias);
        }
    } catch (ResourceStoreException e) {
        throw new CertificateException("", e);
    }
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest,
        final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier)
        throws GeneralSecurityException {
    // obtain the default X509 trust manager
    X509TrustManager defaultTm = null;
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015
    KeyStore ks = null;//from w w w.  j a  v  a 2s . c o  m
    String tsType = System.getProperty("javax.net.ssl.trustStoreType", null);
    if ("Windows-ROOT".equals(tsType)) {
        try {
            ks = KeyStore.getInstance(tsType);
            ks.load(null, null);
            int numEntries = keyStoreAppendIndex(ks);
            logger.info(
                    "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates.");
        } catch (Exception e) {
            logger.error("Could not rename Windows-ROOT aliases", e);
        }
    }

    tmFactory.init(ks);
    for (TrustManager m : tmFactory.getTrustManagers()) {
        if (m instanceof X509TrustManager) {
            defaultTm = (X509TrustManager) m;
            break;
        }
    }
    if (defaultTm == null)
        throw new GeneralSecurityException("No default X509 trust manager found");

    final X509TrustManager tm = defaultTm;

    return new X509TrustManager() {
        private boolean serverCheck;

        public X509Certificate[] getAcceptedIssuers() {
            return tm.getAcceptedIssuers();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = true;
            checkCertTrusted(chain, authType);
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = false;
            checkCertTrusted(chain, authType);
        }

        private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // check and default configurations for property
            // if missing default is null - false
            String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources()
                    .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST);

            if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode)))
                return;

            try {
                // check the certificate itself (issuer, validity)
                try {
                    chain = tryBuildChain(chain);
                } catch (Exception e) {
                } // don't care and take the chain as is

                if (serverCheck)
                    tm.checkServerTrusted(chain, authType);
                else
                    tm.checkClientTrusted(chain, authType);

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext())
                    return;
                else if (serverCheck)
                    serverVerifier.verify(identitiesToTest, chain[0]);
                else
                    clientVerifier.verify(identitiesToTest, chain[0]);

                // ok, globally valid cert
            } catch (CertificateException e) {
                String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM);
                String message = null;
                List<String> propNames = new LinkedList<String>();
                List<String> storedCerts = new LinkedList<String>();
                String appName = R.getSettingsString("service.gui.APPLICATION_NAME");

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) {
                    String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint;
                    propNames.add(propName);

                    message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST",
                            new String[] { appName });

                    // get the thumbprints from the permanent allowances
                    String hashes = config.getString(propName);
                    if (hashes != null)
                        for (String h : hashes.split(","))
                            storedCerts.add(h);

                    // get the thumbprints from the session allowances
                    List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                    if (sessionCerts != null)
                        storedCerts.addAll(sessionCerts);
                } else {
                    if (serverCheck) {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    } else {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    }
                    for (String identity : identitiesToTest) {
                        String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity;
                        propNames.add(propName);

                        // get the thumbprints from the permanent allowances
                        String hashes = config.getString(propName);
                        if (hashes != null)
                            for (String h : hashes.split(","))
                                storedCerts.add(h);

                        // get the thumbprints from the session allowances
                        List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                        if (sessionCerts != null)
                            storedCerts.addAll(sessionCerts);
                    }
                }

                if (!storedCerts.contains(thumbprint)) {
                    switch (verify(chain, message)) {
                    case DO_NOT_TRUST:
                        logger.info("Untrusted certificate", e);
                        throw new CertificateException("The peer provided certificate with Subject <"
                                + chain[0].getSubjectDN() + "> is not trusted", e);
                    case TRUST_ALWAYS:
                        for (String propName : propNames) {
                            String current = config.getString(propName);
                            String newValue = thumbprint;
                            if (current != null)
                                newValue += "," + current;
                            config.setProperty(propName, newValue);
                        }
                        break;
                    case TRUST_THIS_SESSION_ONLY:
                        for (String propName : propNames)
                            getSessionCertEntry(propName).add(thumbprint);
                        break;
                    }
                }
                // ok, we've seen this certificate before
            }
        }

        private X509Certificate[] tryBuildChain(X509Certificate[] chain)
                throws IOException, URISyntaxException, CertificateException {
            // Only try to build chains for servers that send only their
            // own cert, but no issuer. This also matches self signed (will
            // be ignored later) and Root-CA signed certs. In this case we
            // throw the Root-CA away after the lookup
            if (chain.length != 1)
                return chain;

            // ignore self signed certs
            if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN()))
                return chain;

            // prepare for the newly created chain
            List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4);
            for (X509Certificate cert : chain) {
                newChain.add(cert);
            }

            // search from the topmost certificate upwards
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate current = chain[chain.length - 1];
            boolean foundParent;
            int chainLookupCount = 0;
            do {
                foundParent = false;
                // extract the url(s) where the parent certificate can be
                // found
                byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId());
                if (aiaBytes == null)
                    break;

                AuthorityInformationAccess aia = AuthorityInformationAccess
                        .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes));

                // the AIA may contain different URLs and types, try all
                // of them
                for (AccessDescription ad : aia.getAccessDescriptions()) {
                    // we are only interested in the issuer certificate,
                    // not in OCSP urls the like
                    if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers))
                        continue;

                    GeneralName gn = ad.getAccessLocation();
                    if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier
                            && gn.getName() instanceof DERIA5String))
                        continue;

                    URI uri = new URI(((DERIA5String) gn.getName()).getString());
                    // only http(s) urls; LDAP is taken care of in the
                    // default implementation
                    if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https")))
                        continue;

                    X509Certificate cert = null;

                    // try to get cert from cache first to avoid consecutive
                    // (slow) http lookups
                    AiaCacheEntry cache = aiaCache.get(uri);
                    if (cache != null && cache.cacheDate.after(new Date())) {
                        cert = cache.cert;
                    } else {
                        // download if no cache entry or if it is expired
                        if (logger.isDebugEnabled())
                            logger.debug("Downloading parent certificate for <" + current.getSubjectDN()
                                    + "> from <" + uri + ">");
                        try {
                            InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent();
                            cert = (X509Certificate) certFactory.generateCertificate(is);
                        } catch (Exception e) {
                            logger.debug("Could not download from <" + uri + ">");
                        }
                        // cache for 10mins
                        aiaCache.put(uri,
                                new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert));
                    }
                    if (cert != null) {
                        if (!cert.getIssuerDN().equals(cert.getSubjectDN())) {
                            newChain.add(cert);
                            foundParent = true;
                            current = cert;
                            break; // an AD was valid, ignore others
                        } else
                            logger.debug("Parent is self-signed, ignoring");
                    }
                }
                chainLookupCount++;
            } while (foundParent && chainLookupCount < 10);
            chain = newChain.toArray(chain);
            return chain;
        }
    };
}

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

/**
 * Creates Certificate from byte[], can be either an X509 certificate or a CVCCertificate
 *
 * @param cert byte array containing certificate in binary (DER) format, or PEM encoded X.509 certificate
 * @param provider provider for example "SUN" or "BC", use null for the default provider (BC)
 *
 * @return Certificate/* ww w.  jav  a 2 s . c  o  m*/
 *
 * @throws CertificateException if the byte array does not contain a proper certificate.
 * @throws IOException if the byte array cannot be read.
 */
public static Certificate getCertfromByteArray(byte[] cert, String provider) throws CertificateException {
    /*if (log.isTraceEnabled()) {
       log.trace(">getCertfromByteArray");
    }*/
    Certificate ret = null;
    String prov = provider;
    if (provider == null) {
        prov = "BC";
    }
    try {
        CertificateFactory cf = CertTools.getCertificateFactory(prov);
        ret = cf.generateCertificate(new ByteArrayInputStream(cert));
    } catch (CertificateException e) {
        log.debug("CertificateException trying to read X509Certificate.");
    }
    if (ret == null) {
        // We could not create an X509Certificate, see if it is a CVC certificate instead
        try {
            CVCertificate parsedObject = CertificateParser.parseCertificate(cert);
            ret = new CardVerifiableCertificate(parsedObject);
        } catch (ParseException e) {
            log.debug("ParseException trying to read CVCCertificate.");
            throw new CertificateException("Certificate exception trying to read CVCCertificate", e);
        } catch (ConstructionException e) {
            log.debug("ConstructionException trying to read CVCCertificate.");
            throw new CertificateException("Certificate exception trying to read CVCCertificate", e);
        } catch (IllegalArgumentException e) {
            log.debug("CertificateException trying to read CVCCertificate.");
            throw new CertificateException("Certificate exception trying to read CVCCertificate", e);
        }
    }
    if (ret == null) {
        throw new CertificateException("No certificate found");
    }
    //log.trace("<getCertfromByteArray");
    return ret;
}