Example usage for javax.net.ssl KeyManagerFactory init

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

Introduction

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

Prototype

public final void init(KeyStore ks, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Initializes this factory with a source of key material.

Usage

From source file:io.github.thefishlive.updater.HttpServer.java

public void run() {
    try {//from w  w w  .j a v  a  2 s.  c om
        int port = GitUpdater.port;

        // Set up the HTTP protocol processor
        HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
                .add(new ResponseServer("GitUpdater/1.0-SNAPSHOT")).add(new ResponseContent())
                .add(new ResponseConnControl()).build();

        // Set up request handlers
        UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
        reqistry.register("*", new ResponceHandler());

        // Set up the HTTP service
        HttpService httpService = new HttpService(httpproc, reqistry);

        SSLServerSocketFactory sf = null;
        if (port == 8443) {
            // Initialize SSL context
            ClassLoader cl = getClass().getClassLoader();
            URL url = cl.getResource("my.keystore");
            if (url == null) {
                System.out.println("Keystore not found");
                System.exit(1);
            }
            KeyStore keystore = KeyStore.getInstance("jks");
            keystore.load(url.openStream(), "secret".toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, "secret".toCharArray());
            KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            sf = sslcontext.getServerSocketFactory();
        }

        try {
            Thread t = new RequestListenerThread(port, httpService, sf);
            t.setDaemon(false);
            t.start();
        } catch (BindException ex) {
            System.out.println("Error binding to port " + port);
            System.out.println("Perhaps another server is running on that port");
            return;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communications with the server.//from w w w  . j a  va 2s.  co  m
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    String methodName = "createSocket";
    LOGGER.debug("ENTERING: " + methodName);

    LOGGER.debug("trustStoreLoc = " + trustStoreLoc);
    FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
    LOGGER.debug("keyStoreLoc = " + keyStoreLoc);
    FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

    // truststore stuff
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading trustStore");
        trustStore.load(trustFIS, trustStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(trustFIS);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    LOGGER.debug("trust manager factory initialized");

    // keystore stuff
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading keyStore");
        keyStore.load(keyFIS, keyStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyFIS);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePass.toCharArray());
    LOGGER.debug("key manager factory initialized");

    // ssl context
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    LOGGER.debug("EXITING: " + methodName);

    return sslCtx.getSocketFactory();
}

From source file:org.codice.ddf.spatial.ogc.catalog.common.TestTrustedRemoteSource.java

private TLSClientParameters getTLSParameters(KeyStore keyStore, String keystorePassword, KeyStore trustStore) {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {/*from w  w w .j  a v  a  2 s.c o m*/
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        TrustManager[] tm = trustFactory.getTrustManagers();
        tlsParams.setTrustManagers(tm);

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keystorePassword.toCharArray());
        KeyManager[] km = keyFactory.getKeyManagers();
        tlsParams.setKeyManagers(km);
    } catch (Exception e) {
        LOGGER.warn("Could not load keystores, may be an error with the filesystem", e);
    }

    FiltersType filter = new FiltersType();
    filter.getInclude().addAll(SecuritySettingsService.SSL_ALLOWED_ALGORITHMS);
    filter.getExclude().addAll(SecuritySettingsService.SSL_DISALLOWED_ALGORITHMS);
    tlsParams.setCipherSuitesFilter(filter);

    return tlsParams;
}

From source file:org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory.java

private KeyManager[] openKeyStore(String type) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, UnrecoverableKeyException {
    KeyStore keyStore = KeyStore.getInstance(type);
    char[] password = keyStorePassword.toCharArray();
    keyStore.load(new FileInputStream(keyStoreFileName), password);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    return keyManagerFactory.getKeyManagers();
}

From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java

private KeyManager[] createKeyManagers(final KeyStore keyStore, final char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    log.debug("Initializing key managers");

    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keyStore, password);

    return kmfactory.getKeyManagers();
}

From source file:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java

private X509KeyManager getJavaDefaultKeyManager()
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(null, null);

    KeyManager[] x509KeyManagers = keyManagerFactory.getKeyManagers();

    if (x509KeyManagers != null && x509KeyManagers.length > 0) {
        for (int i = 0; i < x509KeyManagers.length; i++) {
            if (x509KeyManagers[i] instanceof X509KeyManager) {
                return (X509KeyManager) x509KeyManagers[i];
            }//  ww  w  .ja  va2s. c  o m
        }
    }

    BetterFORMKeyStoreManager.LOGGER
            .warn("BetterFORMKeyStoreManager: No key managers available for default algorithm.");
    return null;
}

From source file:org.wildfly.elytron.web.undertow.server.ClientCertAuthenticationTest.java

/**
 * Get the key manager backed by the specified key store.
 *
 * @param keystoreName the name of the key store to load.
 * @return the initialised key manager.//w  w w  .  j  a  v a 2  s.c om
 */
private X509ExtendedKeyManager getKeyManager(final String keystorePath) throws Exception {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(loadKeyStore(keystorePath), "Elytron".toCharArray());

    for (KeyManager current : keyManagerFactory.getKeyManagers()) {
        if (current instanceof X509ExtendedKeyManager) {
            return (X509ExtendedKeyManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509ExtendedKeyManager.");
}

From source file:org.apache.felix.karaf.jaas.config.impl.ResourceKeystoreInstance.java

public KeyManager[] getKeyManager(String algorithm, String keyAlias)
        throws KeystoreIsLocked, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    if (isKeystoreLocked()) {
        throw new KeystoreIsLocked("Keystore '" + name + "' is locked.");
    }//from w  w w  .java  2 s  .co  m
    if (!loadKeystoreData()) {
        return null;
    }
    KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(algorithm);
    keyFactory.init(keystore, (char[]) keyPasswords.get(keyAlias));
    return keyFactory.getKeyManagers();
}

From source file:com.screenslicer.common.LenientHttpsConfig.java

private LenientHttpsConfig() {
    AsyncHttpClientConfig configTmp = null;
    SSLContext sslContextTmp = null;
    try {/*www  . j  a  va  2s  .  c  o m*/
        AsyncHttpClient client = new AsyncHttpClient();
        configTmp = client.getConfig();
        IOUtils.closeQuietly(client);
        client = null;

        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert"));
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStore, null);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509");
        trustManager.init(keyStore);
        sslContextTmp = SSLContext.getInstance("TLS");
        sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
    } catch (Throwable t) {
    }
    config = configTmp;
    sslContext = sslContextTmp;
}

From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java

@SuppressWarnings("deprecation")
public SoapUISSLSocketFactory(KeyStore keyStore, String keystorePassword)
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    super(keyStore);

    // trust everyone!
    X509TrustManager tm = new X509TrustManager() {
        @Override// w ww  .  j  a  va  2s.co  m
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    if (keyStore != null) {
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keyStore, keystorePassword != null ? keystorePassword.toCharArray() : null);
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        sslContext.init(keymanagers, new TrustManager[] { tm }, null);
    } else {
        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

}