Example usage for java.security.cert CertificateFactory generateCertificates

List of usage examples for java.security.cert CertificateFactory generateCertificates

Introduction

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

Prototype

public final Collection<? extends Certificate> generateCertificates(InputStream inStream)
        throws CertificateException 

Source Link

Document

Returns a (possibly empty) collection view of the certificates read from the given input stream inStream .

Usage

From source file:osmcd.mapsources.loader.MapPackManager.java

public MapPackManager(File mapPackDir) throws CertificateException, IOException {
    this.mapPackDir = mapPackDir;
    requiredMapPackVersion = Integer.parseInt(System.getProperty("osmcd.mappackversion"));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certs = cf
            .generateCertificates(Utilities.loadResourceAsStream("cert/MapPack.cer"));
    mapPackCert = (X509Certificate) certs.iterator().next();
}

From source file:com.mhise.util.MHISEUtil.java

public static File addBeginEndCertificateTag(Context context, File certfile, String filePath) {
    File updatedFile = null;/* w  w  w.  j  av  a  2 s.c  o  m*/
    java.security.cert.Certificate[] chain = {};

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        FileInputStream ins = new FileInputStream(certfile);
        chain = certificateFactory.generateCertificates(ins).toArray(chain);
        ins.close();

        updatedFile = certfile;
    } catch (CertificateException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag", " CertificateException " + e);
        try {
            String TAG_BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n";
            String TAG_END_CERTIFICATE = "\n-----END CERTIFICATE-----";

            byte[] kb1 = TAG_BEGIN_CERTIFICATE.getBytes();
            byte[] kb3 = TAG_END_CERTIFICATE.getBytes();

            FileInputStream fis = new FileInputStream(certfile);
            int kl = fis.available();
            byte[] kb2 = new byte[kl];
            fis.read(kb2);
            fis.close();

            certfile.delete();
            updatedFile = new File(filePath);
            FileOutputStream fos = new FileOutputStream(filePath);

            ArrayList<byte[]> list = new ArrayList<byte[]>();
            list.add(kb1);
            list.add(kb2);
            list.add(kb3);
            concatenateByteArrays(list);
            fos.write(concatenateByteArrays(list));
            fos.close();

        } catch (IOException e1) {

            Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "Inside catch ->try " + e1);
            return null;
        }

        return updatedFile;
    }

    catch (FileNotFoundException e) {
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "FileNotFoundException " + e);
    } catch (IOException e) {
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "IOException " + e);
    }

    return updatedFile;
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {
    if (name.equals("importCertificateFromFile")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue());
        try {/*  w w  w. j av a  2 s  .  co m*/
            Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator();
            if (it.hasNext()) {
                TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(),
                        (X509Certificate) it.next());
            } else {
                throw new Exception("No certificate found");
            }
        } finally {
            in.close();
        }
        return null;
    } else if (name.equals("retrieveCellCertificate")) {
        DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters));
        String cell = dm.getCell();
        ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance()
                .getConfigQueryExecutor(dm);
        try {
            X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE);
            TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert);
        } finally {
            configQueryExecutor.destroy();
        }
        return null;
    } else if (name.equals("retrieveCertificateFromPort")) {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(new KeyManager[0],
                new TrustManager[] {
                        new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) },
                new SecureRandom());
        SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(
                parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue());
        try {
            socket.startHandshake();
        } finally {
            socket.close();
        }
        return null;
    } else if (name.equals("listCertificates")) {
        final PropertyList certificates = new PropertyList("certificates");
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                // Sort the aliases for convenience
                Set<String> aliases = new TreeSet<String>();
                for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) {
                    aliases.add(e.nextElement());
                }
                for (String alias : aliases) {
                    X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                    PropertyMap map = new PropertyMap("certificate");
                    map.put(new PropertySimple("alias", alias));
                    map.put(new PropertySimple("subject", cert.getSubjectDN().toString()));
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    md.update(cert.getEncoded());
                    byte[] digest = md.digest();
                    StringBuilder fingerprint = new StringBuilder();
                    for (int i = 0; i < digest.length; i++) {
                        if (i > 0) {
                            fingerprint.append(':');
                        }
                        fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4));
                        fingerprint.append(getHexDigit((int) digest[i] & 0x0f));
                    }
                    map.put(new PropertySimple("fingerprint", fingerprint.toString()));
                    certificates.add(map);
                }
            }
        }, true);
        if (log.isDebugEnabled()) {
            log.debug("certificates=" + certificates);
        }
        OperationResult result = new OperationResult();
        result.getComplexResults().put(certificates);
        return result;
    } else if (name.equals("removeCertificate")) {
        final String alias = parameters.getSimple("alias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                truststore.deleteEntry(alias);
            }
        }, false);
        return null;
    } else if (name.equals("renameCertificate")) {
        final String oldAlias = parameters.getSimple("oldAlias").getStringValue();
        final String newAlias = parameters.getSimple("newAlias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                Certificate cert = truststore.getCertificate(oldAlias);
                truststore.setCertificateEntry(newAlias, cert);
                truststore.deleteEntry(oldAlias);
            }
        }, false);
        return null;
    } else {
        return null;
    }
}

From source file:org.qipki.ca.http.presentation.rest.resources.tools.CryptoInspectorResource.java

private boolean isDER(InputStream stream) {
    CertificateFactory certFactory = null;
    try {//from   w  ww  .j  a v a 2s.com
        certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
    } catch (GeneralSecurityException ignored) {
        return false;
    }
    try {
        certFactory.generateCRLs(stream);
        return true;
    } catch (CRLException ignored) {
    }
    try {
        certFactory.generateCertificates(stream);
        return true;
    } catch (CertificateException ignored) {
    }
    // TODO : all other types ........
    return false;
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *//*  w ww . j a  va  2 s.c  o m*/
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}

From source file:com.mhise.util.MHISEUtil.java

public static boolean verifyMobiusChain(String path, Context context) {
    try {//  w  w  w  . j  a  v  a2s.c  om
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        java.security.cert.X509Certificate[] certs = {};
        File file = addBeginEndCertificateTag(context, new File(path), path);
        FileInputStream fis = new FileInputStream(file);
        certs = (X509Certificate[]) certificateFactory.generateCertificates(fis).toArray(certs);
        fis.close();
        boolean flag = false;

        for (int i = 0; i < certs.length; i++) {
            if (certs[i].getIssuerDN().toString().contains("MobiusCA")) {
                flag = true;
            } else {
                flag = false;
            }
        }
        return flag;

    } catch (Exception e) {
        e.printStackTrace();
        Logger.debug("MHISEUtil-->TAG", "Exception path : " + path);
    }

    return false;
}

From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java

public void getCredentials(byte[] derEncodedCertRequest) throws IOException, GeneralSecurityException {
    try {//from  w  w  w  .  j  av  a 2s . c  o m

        if (this.state != State.LOGGEDON) {
            this.logon();
        }

        this.socketOut.write(derEncodedCertRequest);
        this.socketOut.flush();
        int numCertificates = this.socketIn.read();
        if (numCertificates == -1) {
            System.err.println("connection aborted");
            throw new IOException("Error: connection aborted");
        } else if (numCertificates == 0 || numCertificates < 0) {
            System.err.print("bad number of certificates sent by server: ");
            System.err.println(Integer.toString(numCertificates));
            throw new GeneralSecurityException("Error: bad number of certificates sent by server");
        }
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        this.certificateChain = (Collection<X509Certificate>) certFactory.generateCertificates(this.socketIn);
        this.state = State.DONE;
    } catch (Throwable t) {
        handleException(t, getClass().getSimpleName() + " failure getting the credential.");
    }
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

void importPrivateKey(String keyAlias, String keyPassword, InputStream fl, InputStream certstream)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException,
        KeyStoreException {/*  ww w.  ja v  a  2 s  .c  om*/
    KeyInfoManager keyInfoManager = null;

    writeLock.lock();
    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        // loading Key
        byte[] keyBytes = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(keyBytes, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey key = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        @SuppressWarnings("rawtypes")
        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        certs = (Certificate[]) c.toArray(new Certificate[0]);

        // storing keystore
        ks.setKeyEntry(keyAlias, key, keyPassword.toCharArray(), certs);

        if (logger.isDebugEnabled()) {
            logger.debug("Key and certificate stored.");
            logger.debug("Alias:" + keyAlias);
        }

        ks.store(new FileOutputStream(getKeyStoreParameters().getLocation()), keyPassword.toCharArray());
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }

        writeLock.unlock();
    }
}

From source file:io.swagger.client.ApiClient.java

/**
 * Apply SSL related settings to httpClient according to the current values of
 * verifyingSsl and sslCaCert.//from   www  .  j av  a 2 s .  c  o  m
 */
private void applySslSettings() {
    try {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;
        HostnameVerifier hostnameVerifier = null;
        if (!verifyingSsl) {
            TrustManager trustAll = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            trustManagers = new TrustManager[] { trustAll };
            hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
        } else if (sslCaCert != null) {
            char[] password = null; // Any password will work.
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
            if (certificates.isEmpty()) {
                throw new IllegalArgumentException("expected non-empty set of trusted certificates");
            }
            KeyStore caKeyStore = newEmptyKeyStore(password);
            int index = 0;
            for (Certificate certificate : certificates) {
                String certificateAlias = "ca" + Integer.toString(index++);
                caKeyStore.setCertificateEntry(certificateAlias, certificate);
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(caKeyStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        }

        if (keyManagers != null || trustManagers != null) {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagers, trustManagers, new SecureRandom());
            httpClient.setSslSocketFactory(sslContext.getSocketFactory());
        } else {
            httpClient.setSslSocketFactory(null);
        }
        httpClient.setHostnameVerifier(hostnameVerifier);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java

public void deleteRevokedCertificates() {

    if (truststore != null) {
        // Delete the old revoked or unnecessary BioCatalogue,
        // BiodiversityCatalogue and heater's certificates, if present

        if (certificatesRevokedIndicatorFile == null) {
            certificatesRevokedIndicatorFile = new File(credentialManagerDirectory,
                    CERTIFICATES_REVOKED_INDICATOR_FILE_NAME);
        }//w  w  w.  j  a v  a2  s.  c  o m

        if (!certificatesRevokedIndicatorFile.exists()) {

            List<URL> certURLsToDelete = new ArrayList<>();
            Class<?> c = CredentialManager.class;
            //certURLsToDelete.add(c.getResource("/trusted-certificates/www.biocatalogue.org-revoked.pem"));
            //certURLsToDelete.add(c.getResource("/trusted-certificates/www.biodiversitycatalogue.org-revoked.pem"));
            //certURLsToDelete.add(c.getResource("/trusted-certificates/heater.cs.man.ac.uk-not-needed.pem"));

            for (URL certURLToDelete : certURLsToDelete) {
                try (InputStream certStreamToDelete = certURLToDelete.openStream()) {
                    // We know there will be only one cert in the chain
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    Certificate certToDelete = cf.generateCertificates(certStreamToDelete)
                            .toArray(new Certificate[0])[0];
                    String aliasToDelete = truststore.getCertificateAlias(certToDelete);
                    if (aliasToDelete != null) {
                        truststore.deleteEntry(aliasToDelete);
                        logger.warn("Deleting revoked/unnecessary certificate " + aliasToDelete);
                    }
                } catch (Exception ex) {
                    logger.info("Can't delete revoked certificate " + certURLToDelete, ex);
                }
            }

            // Touch the file
            try {
                FileUtils.touch(certificatesRevokedIndicatorFile);
            } catch (IOException ioex) {
                // Hmmm, ignore this?
                logger.error("Failed to touch " + certificatesRevokedIndicatorFile.getAbsolutePath(), ioex);
            }
        }

        //Save changes
        try {
            FileOutputStream fos = new FileOutputStream(truststoreFile);
            truststore.store(fos, masterPassword.toCharArray());
        } catch (Exception ex) {
            String exMessage = "Failed to save Truststore after deleting revoked certificates.";
            logger.error(exMessage, ex);
        }
    }
}