Example usage for javax.net.ssl KeyManagerFactory getInstance

List of usage examples for javax.net.ssl KeyManagerFactory getInstance

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getInstance.

Prototype

public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

Usage

From source file:net.lightbody.bmp.proxy.jetty.http.SslListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    SSLContext context;/*  w  ww.  ja v  a 2  s  . co m*/
    if (_provider == null) {
        context = SSLContext.getInstance(_protocol);
    } else {
        context = SSLContext.getInstance(_protocol, _provider);
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_algorithm);
    KeyStore keyStore = KeyStore.getInstance(_keystoreType);
    keyStore.load(Resource.newResource(_keystore).getInputStream(), _password.toString().toCharArray());
    keyManagerFactory.init(keyStore, _keypassword.toString().toCharArray());

    context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());

    return context.getServerSocketFactory();
}

From source file:org.springframework.integration.x.http.NettyHttpInboundChannelAdapter.java

private SSLContext initializeSSLContext() throws Exception {
    Assert.state(this.sslPropertiesLocation != null, "KeyStore and pass phrase properties file required");
    Properties sslProperties = new Properties();
    sslProperties.load(this.sslPropertiesLocation.getInputStream());
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    String keyStoreName = sslProperties.getProperty("keyStore");
    Assert.state(StringUtils.hasText(keyStoreName), "keyStore property cannot be null");
    String keyStorePassPhrase = sslProperties.getProperty("keyStore.passPhrase");
    Assert.state(StringUtils.hasText(keyStorePassPhrase), "keyStore.passPhrase property cannot be null");
    Resource keyStore = resolver.getResource(keyStoreName);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(keyStore.getInputStream(), keyStorePassPhrase.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, keyStorePassPhrase.toCharArray());
    sslContext.init(kmf.getKeyManagers(), null, null);
    return sslContext;
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLSender.java

private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert)
        throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    if (keyStoreElt != null) {
        String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {//from  w ww  .  ja v  a2s  .c  o  m
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Identity Keystore from : " + location);

            keyStore.load(fis, storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Keystore : " + location, gse);
            throw new AxisFault("Error loading Keystore : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Keystore : " + location, ioe);
            throw new AxisFault("Error opening Keystore : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreElt != null) {
        if (novalidatecert) {
            log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
        }

        String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText();

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Trust Keystore from : " + location);

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    } else if (novalidatecert) {
        log.warn("Server certificate validation (trust) has been disabled. " + "DO NOT USE IN PRODUCTION!");
        trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
    }

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error("Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

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

/**
 * Generate a socket factory using supplied key and trust stores 
 *///from  w ww  . j a v  a2  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.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClientConnectionManager createConnectionManager() {
    PoolingHttpClientConnectionManager manager;
    if ("https".equals(graphiteScheme) && !StringUtils.isEmpty(graphiteKeyStore)
            && !StringUtils.isEmpty(graphiteKeyStorePassword) && !StringUtils.isEmpty(graphiteTrustStore)) {
        try {/*from   ww  w. jav  a2  s.co m*/
            KeyStore keyStore = loadKeyStore(graphiteKeyStore, graphiteKeyStorePassword);
            KeyStore trustStore = loadKeyStore(graphiteTrustStore, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, graphiteKeyStorePassword.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(keyManagers, trustManagers, null);

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("https", sslsf).build();

            manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (Exception e) {
            LOGGER.warn("A problem occurred when building SSLConnectionSocketFactory", e);
            throw new RuntimeException("Error while building SSLConnectionSocketFactory", e);
        }
    } else {
        manager = new PoolingHttpClientConnectionManager();
    }

    manager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    return manager;
}

From source file:org.exoplatform.services.videocall.AuthService.java

protected static KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile,
        String keyStorePassword) throws Exception {
    KeyStore keyStore = null;/*from w  w w.j  a v  a 2  s. c o  m*/
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate PKCS12 keystores");
        }
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate PKCS12 keystores");
        }
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Bad key or certificate in " + keyStoreFile, e.getMessage());
        }
    } catch (FileNotFoundException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not find or read " + keyStoreFile, e.getMessage());
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("PKCS12 password is incorrect or keystore is inconsistent: " + keyStoreFile);
        }
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePassword.toCharArray());
    return kmf.getKeyManagers();
}

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Configure {@link SSLContext} and create EJB client properties.
 *
 * @param clientName// w w  w  .  jav  a2 s. c o  m
 * @return
 * @throws Exception
 */
private Properties configureEjbClient(String clientName) throws Exception {
    // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(
            KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()),
            KEYSTORE_PASSWORD.toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory
            .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);

    final Properties env = new Properties();
    env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
    env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST);
    env.put("jboss.naming.client.ejb.context", "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "testing");

    // SSL related config parameters
    env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
            "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
    return env;
}

From source file:com.isecpartners.gizmo.HttpRequest.java

private KeyManagerFactory createKeyManagerFactory(String cname) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException,
        InvalidKeyException, SignatureException, NoSuchProviderException, NoCertException {
    X509Certificate cert = KeyStoreManager.getCertificateByHostname(cname);
    cybervillains.ca.KeyStoreManager.getCertificateByHostname(cname);

    if (cert == null) {
        throw new NoCertException();
    }//from  w w  w.  j  a  v  a2s .c  o  m

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, pass);

    ks.setCertificateEntry(cname, cert);
    ks.setKeyEntry(cname, KeyStoreManager.getPrivateKeyForLocalCert(cert), pass,
            new X509Certificate[] { cert });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, pass);

    return kmf;
}

From source file:org.sandrob.android.net.http.HttpsConnection.java

/**
 * /*  w  ww. j a va  2s .co  m*/
 *
 * @param sessionDir directory to cache SSL sessions
 * @param req request that call this function
 */
public void initializeEngine(File sessionDir, Request req) {
    if (mSslSocketFactory == null) {
        String certificateFullPathName = null;
        String keyStoreType = "PKCS12";
        String keyStoreProvider = "BC";
        String certificatePassword = null;
        try {
            SSLClientSessionCache cache = null;
            KeyManager[] keyManagers = null;
            KeyStore keyStore = null;
            if (sessionDir != null) {
                Log.d("HttpsConnection", "Caching SSL sessions in " + sessionDir + ".");
                cache = FileClientSessionCache.usingDirectory(sessionDir);
            }

            // Inform the user if we need ssl client settings
            if (true) {

                synchronized (mSuspendLock) {
                    mSuspended = true;
                }
                // don't hold the lock while calling out to the event handler
                boolean canHandle = req.getEventHandler().handleSslClientSetingsRequest();
                if (!canHandle) {
                    throw new IOException("failed to handle ssl client settings ");
                }
                synchronized (mSuspendLock) {
                    if (mSuspended) {
                        try {
                            // Put a limit on how long we are waiting; if the timeout
                            // expires (which should never happen unless you choose
                            // to ignore the SSL error dialog for a very long time),
                            // we wake up the thread and abort the request. This is
                            // to prevent us from stalling the network if things go
                            // very bad.
                            mSuspendLock.wait(10 * 60 * 1000);
                            if (mSuspended) {
                                // mSuspended is true if we have not had a chance to
                                // restart the connection yet (ie, the wait timeout
                                // has expired)
                                mSuspended = false;
                                mAborted = true;
                                if (HttpLog.LOGV) {
                                    HttpLog.v("HttpsConnection.openConnection():"
                                            + " SSL timeout expired and request was cancelled!!!");
                                }
                            }
                        } catch (InterruptedException e) {
                            // ignore
                        }
                    }
                    if (mAborted) {
                        // The user decided not to use this unverified connection
                        // so close it immediately.
                        throw new SSLConnectionClosedByUserException("connection closed by the user");
                    }
                    if (mSslClientCertificate != null) {
                        // we have some data about client certificate
                        certificateFullPathName = mSslClientCertificate.getCertificateFileName();
                        certificatePassword = mSslClientCertificate.getCertificateFilePassword();
                    }
                }
            }

            SSLContextImpl sslContext = new SSLContextImpl();
            //SSLContext sslContext = SSLContext.getInstance("TLS");
            if (certificateFullPathName != null && certificatePassword != null) {
                File certFile = new File(certificateFullPathName);
                if (certFile.exists()) {
                    keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider);
                    keyStore.load(new FileInputStream(new File(certificateFullPathName)),
                            certificatePassword.toCharArray());

                    String kmfa = KeyManagerFactory.getDefaultAlgorithm();
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfa);
                    kmf.init(keyStore, certificatePassword.toCharArray());
                    keyManagers = kmf.getKeyManagers();
                }
            }

            // here, trust managers is a single trust-all manager
            TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

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

            sslContext.engineInit(keyManagers, trustManagers, null, cache, null);
            //sslContext.init(keyManagers, trustManagers, null);
            synchronized (HttpsConnection.class) {
                mSslSocketFactory = sslContext.engineGetSocketFactory();
                //mSslSocketFactory = sslContext.getSocketFactory();
            }
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}