Example usage for javax.net.ssl KeyManagerFactory getKeyManagers

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

Introduction

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

Prototype

public final KeyManager[] getKeyManagers() 

Source Link

Document

Returns one key manager for each type of key material.

Usage

From source file:org.appenders.log4j2.elasticsearch.jest.JKSCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder clientConfigBuilder) {

    try (FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

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

        // TODO: add support for hostname verification modes
        clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        clientConfigBuilder/*w  ww . ja va2 s. com*/
                .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}

From source file:org.opennms.netmgt.provision.server.SSLServer.java

/**
 * <p>init</p>/*from   w w w .j  a  v  a  2  s  .  com*/
 *
 * @throws java.lang.Exception if any.
 */
@Override
public void init() throws Exception {
    super.init();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(getKeyManagerAlgorithm(), getKeyManagerProvider());
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] password = getPassword().toCharArray();

    java.io.FileInputStream fis = null;
    try {
        fis = new java.io.FileInputStream(getPathToKeyStore());
        ks.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    kmf.init(ks, password);
    KeyManager[] km = kmf.getKeyManagers();

    SSLContext sslContext = SSLContext.getInstance(getSslContextProtocol());
    sslContext.init(km, null, new SecureRandom());
    SSLServerSocketFactory serverFactory = sslContext.getServerSocketFactory();
    setServerSocket(serverFactory.createServerSocket(getPort()));
    onInit();
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) {
    SSLSocket socket;/*from ww w. j  av a  2  s  . c o m*/
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        //          keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());

        // This works when built with Eclipse, but not when built from command line. 
        // Has to do with where the build system puts /resources/*.p12 file
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray());

        // Currently only works when read from the server's FS. Won't currently read from within eclipse project. 
        // Putting it in /opt/kme/push prevents naming conflicts. 
        keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
        keyManagerFactory.init(keyStore, "strange word to use".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
        trustManagerFactory.init(keyStore);
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        //Diagnostic output
        Enumeration e = keyStore.aliases();
        LOG.info(e.toString());
        while (e.hasMoreElements()) {
            LOG.info("Alias: " + e.nextElement().toString());
        }

        String not = (socket.isConnected()) ? "" : "NOT ";
        LOG.info("SSLSocket is " + not + "Connected");

        LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName());
        LOG.info("Connected to: " + socket.getInetAddress().getHostAddress());

        String cs[] = socket.getEnabledCipherSuites();
        LOG.info("CipherSuites: " + Arrays.toString(cs));

        String ep[] = socket.getEnabledProtocols();
        LOG.info("Enabled Protocols: " + Arrays.toString(ep));

        LOG.info("Timeout: " + socket.getSoTimeout());
        LOG.info("Send Buffer Size: " + socket.getSendBufferSize());

        return socket;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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

/**
 * //from   w  ww .ja v a  2  s . c o  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);
        }
    }
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

public DatabaseSSLProviderImpl(KeystoreConfig keystoreConfig, boolean acceptUnverifiedCertificates) {
    if (log.isDebugEnabled()) {
        log.debug("Keystore info: alias=" + keystoreConfig.getAlias() + ", path:" + keystoreConfig.getFilePath()
                + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates);
    }//from ww w.  j a  v  a2  s . c o  m
    boolean hasLock = false;
    final boolean debug = log.isDebugEnabled();
    final StopWatch watch = new StopWatch();
    try {
        KeystoreManager keystoreMgr = KeystoreManager.getKeystoreManager();
        KEYSTORE_READER_LOCK.lockInterruptibly();
        hasLock = true;
        KeyStore trustStore = keystoreMgr.getKeyStore(keystoreConfig);
        KeyManagerFactory keyManagerFactory = getKeyManagerFactory(trustStore,
                keystoreConfig.getFilePassword());
        TrustManagerFactory trustManagerFactory = getTrustManagerFactory(trustStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        X509TrustManager customTrustManager = getCustomTrustManager(defaultTrustManager, keystoreConfig,
                acceptUnverifiedCertificates, trustStore);
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { customTrustManager },
                new SecureRandom());
        // XXX Should we use ALLOW_ALL_HOSTNAME_VERIFIER (least restrictive) or 
        //     BROWSER_COMPATIBLE_HOSTNAME_VERIFIER (moderate restrictive) or
        //     STRICT_HOSTNAME_VERIFIER (most restrictive)???
        sslSocketFactory = new SSLSocketFactory(sslContext, getHostnameVerifier());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        if (hasLock)
            KEYSTORE_READER_LOCK.unlock();
        if (debug)
            log.debug("readCert: " + watch);
    }
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

private X509KeyManager getX509KeyManager(final File keyStore, final char[] keyStorePassword)
        throws GeneralSecurityException, IOException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(loadKeyStore(keyStore), keyStorePassword);
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            return (X509KeyManager) keyManager;
        }//  ww  w.ja  v a2  s.  co  m
    }
    return null;
}

From source file:edu.washington.iam.tools.IamConnectionManager.java

protected void initManagers() {

    // trust managers
    /**/*  w  w  w . ja v  a 2  s .c  o  m*/
           try {
               TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            
               X509Certificate cert = null;
               if (caFilename!=null) cert = readCertificate(caFilename);
               log.debug("init trust mgr " + cert);
               trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
               trustStore.load(null, null);
               trustStore.setCertificateEntry("CACERT", cert);
               tmf.init(trustStore);
               trustManagers = tmf.getTrustManagers();
           } catch (Exception e) {
               log.error("cacert error: " + e);
           }
     **/
    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 managers
    if (certFilename != null && keyFilename != null) {
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            X509Certificate cert = readCertificate(certFilename);
            PKCS1 pkcs = new PKCS1();
            PrivateKey key = pkcs.readKey(keyFilename);

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

            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        } catch (Exception e) {
            log.error("cert/key error: " + e);
        }
    }

}

From source file:org.apache.james.protocols.lib.netty.AbstractConfigurableAsyncServer.java

/**
 * Build the SSLEngine/* w  w w.jav a 2  s.  c  o  m*/
 * 
 * @throws Exception
 */

private void buildSSLContext() throws Exception {
    if (useStartTLS || useSSL) {
        FileInputStream fis = null;
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            fis = new FileInputStream(fileSystem.getFile(keystore));
            ks.load(fis, secret.toCharArray());

            // Set up key manager factory to use our key store
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(x509Algorithm);
            kmf.init(ks, secret.toCharArray());

            // Initialize the SSLContext to work with our key managers.
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(kmf.getKeyManagers(), null, null);
            if (useStartTLS) {
                encryption = Encryption.createStartTls(context, enabledCipherSuites);
            } else {
                encryption = Encryption.createTls(context, enabledCipherSuites);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }
}

From source file:mitm.common.security.ca.handlers.ejbca.EJBCACertificateRequestHandler.java

private EjbcaWS getEjbcaWS() throws CAException {
    if (ejbcaWS == null) {
        try {/*from  w  ww.  ja  v a2 s.c  o  m*/
            JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

            factory.setServiceClass(EjbcaWS.class);
            factory.setAddress(requestHandlerSettings.getWebServiceURL().toExternalForm());
            factory.setServiceName(EJBCAConst.SERVICE_NAME);
            EjbcaWS localEjbcaWS = (EjbcaWS) factory.create();

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());

            char[] password = requestHandlerSettings.getKeyStorePassword() != null
                    ? requestHandlerSettings.getKeyStorePassword().toCharArray()
                    : null;

            keyManagerFactory.init(requestHandlerSettings.getKeyStore(), password);

            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            Client proxy = ClientProxy.getClient(localEjbcaWS);

            TLSClientParameters tlsClientParameters = new TLSClientParameters();

            tlsClientParameters.setDisableCNCheck(requestHandlerSettings.isDisableCNCheck());

            if (requestHandlerSettings.isSkipCertificateCheck()) {
                /*
                 * Use a TrustManager that skips all checks 
                 */
                tlsClientParameters.setTrustManagers(new TrustManager[] { new TrustAllX509TrustManager() });
            } else {
                KeyStore trustStore = requestHandlerSettings.getTrustStore();

                if (trustStore != null) {
                    /*
                     * Use the provided trust store
                     */
                    TrustManagerFactory trustManagerFactory = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

                    trustManagerFactory.init(trustStore);

                    tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers());
                }
            }

            tlsClientParameters.setKeyManagers(keyManagers);

            HTTPConduit conduit = (HTTPConduit) proxy.getConduit();

            conduit.setTlsClientParameters(tlsClientParameters);

            ejbcaWS = localEjbcaWS;
        } catch (NoSuchAlgorithmException e) {
            throw new CAException(e);
        } catch (UnrecoverableKeyException e) {
            throw new CAException(e);
        } catch (KeyStoreException e) {
            throw new CAException(e);
        }
    }

    return ejbcaWS;
}