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.hyperic.util.security.DefaultSSLProviderImpl.java

public DefaultSSLProviderImpl(KeystoreConfig keystoreConfig, boolean acceptUnverifiedCertificates) {
    if (log.isDebugEnabled()) {
        log.debug("Keystore info: alias=" + keystoreConfig.getAlias() + ", acceptUnverifiedCertificates="
                + acceptUnverifiedCertificates);
    }/*w  ww.  ja v  a 2 s.  c  o m*/
    final boolean debug = log.isDebugEnabled();
    final StopWatch watch = new StopWatch();
    try {
        KeystoreManager keystoreMgr = KeystoreManager.getKeystoreManager();
        KeyStore trustStore = keystoreMgr.getKeyStore(keystoreConfig);
        KeyManagerFactory keyManagerFactory = getKeyManagerFactory(trustStore,
                keystoreConfig.getFilePassword());
        TrustManagerFactory trustManagerFactory = getTrustManagerFactory(trustStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        X509TrustManager customTrustManager = keystoreMgr.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 (debug)
            log.debug("readCert: " + watch);
    }
}

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

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

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }/* ww w  . j  a v a2  s  .c om*/

    try (FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

        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
        builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

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

}

From source file:org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean.java

/**
 * Override this method to take complete control over the SSL setup.
 * @throws Exception an Exception.//from w w w  . j  av  a  2  s  .c om
 * @since 1.4.4
 */
protected void setUpSSL() throws Exception {
    if (this.sslPropertiesLocation == null && this.keyStore == null && this.trustStore == null
            && this.keyStoreResource == null && this.trustStoreResource == null) {
        if (this.sslAlgorithmSet) {
            this.connectionFactory.useSslProtocol(this.sslAlgorithm);
        } else {
            this.connectionFactory.useSslProtocol();
        }
    } else {
        if (this.sslPropertiesLocation != null) {
            this.sslProperties.load(this.sslPropertiesLocation.getInputStream());
        }
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String keyStoreName = getKeyStore();
        String trustStoreName = getTrustStore();
        String keyStorePassword = getKeyStorePassphrase();
        String trustStorePassword = getTrustStorePassphrase();
        String keyStoreType = getKeyStoreType();
        String trustStoreType = getTrustStoreType();
        char[] keyPassphrase = null;
        if (StringUtils.hasText(keyStorePassword)) {
            keyPassphrase = keyStorePassword.toCharArray();
        }
        char[] trustPassphrase = null;
        if (StringUtils.hasText(trustStorePassword)) {
            trustPassphrase = trustStorePassword.toCharArray();
        }
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;
        if (StringUtils.hasText(keyStoreName) || this.keyStoreResource != null) {
            Resource keyStoreResource = this.keyStoreResource != null ? this.keyStoreResource
                    : resolver.getResource(keyStoreName);
            KeyStore ks = KeyStore.getInstance(keyStoreType);
            ks.load(keyStoreResource.getInputStream(), keyPassphrase);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, keyPassphrase);
            keyManagers = kmf.getKeyManagers();
        }
        if (StringUtils.hasText(trustStoreName) || this.trustStoreResource != null) {
            Resource trustStoreResource = this.trustStoreResource != null ? this.trustStoreResource
                    : resolver.getResource(trustStoreName);
            KeyStore tks = KeyStore.getInstance(trustStoreType);
            tks.load(trustStoreResource.getInputStream(), trustPassphrase);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(tks);
            trustManagers = tmf.getTrustManagers();
        }

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Initializing SSLContext with KM: " + Arrays.toString(keyManagers) + ", TM: "
                    + Arrays.toString(trustManagers) + ", random: " + this.secureRandom);
        }
        SSLContext context = createSSLContext();
        context.init(keyManagers, trustManagers, this.secureRandom);
        this.connectionFactory.useSslProtocol(context);
    }
}

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

protected SSLServerSocketFactory createFactory() throws Exception {
    SSLContext context;//from www .  j a  v  a2  s  . com
    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:com.hypersocket.server.HypersocketServerImpl.java

public void initializeSSL() throws FileNotFoundException, IOException {

    CertificateResourceService certificateService = (CertificateResourceService) applicationContext
            .getBean("certificateResourceServiceImpl");
    RealmService realmService = (RealmService) applicationContext.getBean("realmServiceImpl");

    certificateService.setCurrentPrincipal(realmService.getSystemPrincipal(), Locale.getDefault(),
            realmService.getSystemPrincipal().getRealm());

    try {//from w w w . j a  v a 2s.  c  o m

        if (log.isInfoEnabled()) {
            log.info("Initializing SSL contexts");
        }

        KeyStore ks = certificateService.getDefaultCertificate();

        // Get the default context
        defaultSSLContext = SSLContext.getInstance("TLS");

        // KeyManager's decide which key material to use.
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, "changeit".toCharArray());
        defaultSSLContext.init(kmf.getKeyManagers(), null, null);

        if (log.isInfoEnabled()) {
            log.info("Completed SSL initialization");
        }
    } catch (Exception ex) {
        log.error("SSL initalization failed", ex);
        throw new IOException("SSL initialization failed: " + ex.getMessage());
    } finally {
        certificateService.clearPrincipalContext();
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@After
// Clean up the credentialManagerDirectory we created for testing
public void cleanUp() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException,
        KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    //      assertTrue(credentialManagerDirectory.exists());
    //      assertFalse(credentialManagerDirectory.listFiles().length == 0); // something was created there

    if (credentialManagerDirectory.exists()) {
        try {//from ww  w  . j a  va 2 s  .com
            FileUtils.deleteDirectory(credentialManagerDirectory);
            System.out.println(
                    "Deleting Credential Manager's directory: " + credentialManagerDirectory.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }
    }

    // Reset the SSLSocketFactory in JVM so we always have a clean start
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSLv3");

    // Create a "default" JSSE X509KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    kmf.init(ks, "blah".toCharArray());

    // Create a "default" JSSE X509TrustManager.
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(null, null);
    tmf.init(ts);

    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    SSLContext.setDefault(sc);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

From source file:it.jnrpe.server.CBindingThread.java

/**
 * Returns the SSL factory to be used to create the Server Socket
 * @throws KeyStoreException /*from w  ww  . j  av  a  2  s . co m*/
 * @throws IOException 
 * @throws FileNotFoundException 
 * @throws CertificateException 
 * @throws UnrecoverableKeyException 
 * @throws KeyManagementException 
 * 
 * @see it.intesa.fi2.client.network.ISSLObjectsFactory#getSSLSocketFactory(String, String, String)
 */
public SSLServerSocketFactory getSSLSocketFactory(String sKeyStoreFile, String sKeyStorePwd,
        String sKeyStoreType) throws KeyStoreException, CertificateException, FileNotFoundException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    if (sKeyStoreFile == null)
        throw new KeyStoreException("KEYSTORE HAS NOT BEEN SPECIFIED");
    if (this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile) == null)
        throw new KeyStoreException("COULD NOT FIND KEYSTORE '" + sKeyStoreFile + "'");

    if (sKeyStorePwd == null)
        throw new KeyStoreException("KEYSTORE PASSWORD HAS NOT BEEN SPECIFIED");

    SSLContext ctx;
    KeyManagerFactory kmf;

    try {
        ctx = SSLContext.getInstance("SSLv3");

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

        //KeyStore ks = getKeystore(sKeyStoreFile, sKeyStorePwd, sKeyStoreType);
        KeyStore ks = KeyStore.getInstance(sKeyStoreType);
        ks.load(this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile),
                sKeyStorePwd.toCharArray());

        char[] passphrase = sKeyStorePwd.toCharArray();
        kmf.init(ks, passphrase);
        ctx.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());

    } catch (NoSuchAlgorithmException e) {
        throw new SSLException("Unable to initialize SSLSocketFactory.\n" + e.getMessage());
    }

    return ctx.getServerSocketFactory();
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private void configureSSL(HttpClient client) throws IOException {
    final String keyStorePath = System.getProperty("javax.net.ssl.keyStore");
    final String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
    final boolean validateSSLCertificates = StringUtils.hasText(keyStorePath)
            && StringUtils.hasText(keyStorePassword);

    X509TrustManager customTrustManager = null;
    KeyManager[] keyManagers = null;

    try {//from w w w. j a  va  2 s  .  co m
        if (validateSSLCertificates) {
            // Use specified key store and perform SSL validation...
            KeyStore keystore = getKeyStore(keyStorePath, keyStorePassword);
            KeyManagerFactory keyManagerFactory = getKeyManagerFactory(keystore, keyStorePassword);
            TrustManagerFactory trustManagerFactory = getTrustManagerFactory(keystore);

            keyManagers = keyManagerFactory.getKeyManagers();
            customTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        } else {
            // Revert to previous functionality and ignore SSL certs...
            customTrustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

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

                //required for jdk 1.3/jsse 1.0.3_01
                public boolean isClientTrusted(X509Certificate[] chain) {
                    return true;
                }

                //required for jdk 1.3/jsse 1.0.3_01
                public boolean isServerTrusted(X509Certificate[] chain) {
                    return true;
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
        }

        SSLContext sslContext = SSLContext.getInstance("TLS");

        sslContext.init(keyManagers, 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)???
        // For now allow all, and make it configurable later...

        X509HostnameVerifier hostnameVerifier = null;

        if (validateSSLCertificates) {
            hostnameVerifier = new AllowAllHostnameVerifier();
        } else {
            hostnameVerifier = new X509HostnameVerifier() {
                private AllowAllHostnameVerifier internalVerifier = new AllowAllHostnameVerifier();

                public boolean verify(String host, SSLSession session) {
                    return internalVerifier.verify(host, session);
                }

                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    internalVerifier.verify(host, cns, subjectAlts);
                }

                public void verify(String host, X509Certificate cert) throws SSLException {
                    internalVerifier.verify(host, cert);
                }

                public void verify(String host, SSLSocket ssl) throws IOException {
                    try {
                        internalVerifier.verify(host, ssl);
                    } catch (SSLPeerUnverifiedException e) {
                        // ignore
                    }
                }
            };
        }

        client.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", 443, new SSLSocketFactory(sslContext, hostnameVerifier)));
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java

private void configureHttps(WebClient client) {
    LOGGER.debug("Configuring client for HTTPS");
    HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
    if (null != conduit) {
        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
        }//from   w w  w . j a v a  2s . com

        params.setDisableCNCheck(true);

        KeyStore keyStore;
        KeyStore trustStore;
        FileInputStream tsFIS = null;
        FileInputStream ksFIS = null;
        try {
            String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
            String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
            String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");

            trustStore = KeyStore.getInstance(trustStoreType);
            File trustStoreFile = new File(trustStorePath);
            tsFIS = new FileInputStream(trustStoreFile);
            trustStore.load(tsFIS, trustStorePassword.toCharArray());

            String keyStorePath = System.getProperty("javax.net.ssl.keyStore");
            String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
            String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");

            keyStore = KeyStore.getInstance(keyStoreType);
            File keyStoreFile = new File(keyStorePath);
            ksFIS = new FileInputStream(keyStoreFile);
            keyStore.load(ksFIS, keyStorePassword.toCharArray());

            TrustManagerFactory trustFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustFactory.init(trustStore);
            TrustManager[] tm = trustFactory.getTrustManagers();
            params.setTrustManagers(tm);

            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyFactory.init(keyStore, keyStorePassword.toCharArray());
            KeyManager[] km = keyFactory.getKeyManagers();
            params.setKeyManagers(km);

            conduit.setTlsClientParameters(params);
        } catch (KeyStoreException e) {
            handleKeyStoreException(e);
        } catch (NoSuchAlgorithmException e) {
            handleKeyStoreException(e);
        } catch (CertificateException e) {
            handleKeyStoreException(e);
        } catch (FileNotFoundException e) {
            handleKeyStoreException(e);
        } catch (IOException e) {
            handleKeyStoreException(e);
        } catch (UnrecoverableKeyException e) {
            handleKeyStoreException(e);
        } finally {
            if (null != tsFIS) {
                IOUtils.closeQuietly(tsFIS);
            }
            if (null != ksFIS) {
                IOUtils.closeQuietly(ksFIS);
            }
        }
    } else {
        LOGGER.warn("HTTP Conduit returned by the web client was NULL.");
    }
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * This attempts to load the KeyManagers from the supplied <code>
 * InputStream</code> using the supplied password.
 *
 * @param  is  <code>InputStream</code> containing the keystore
 * @param  password  <code>String</code> to unlock the keystore
 * @param  storeType  <code>String</code> of keystore
 *
 * @return  <code>KeyManager[]</code>
 *
 * @throws  IOException  if the keystore cannot be loaded
 * @throws  GeneralSecurityException  if an errors occurs while loading the
 * KeyManagers/*w  w  w. java  2  s.  c o  m*/
 */
private KeyManager[] initKeyManager(final InputStream is, final String password, final String storeType)
        throws IOException, GeneralSecurityException {
    KeyManager[] km = null;
    if (is != null) {
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(this.loadKeyStore(is, password, storeType), password != null ? password.toCharArray() : null);
        km = kmf.getKeyManagers();
    }
    return km;
}