Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

List of usage examples for javax.net.ssl TrustManagerFactory getTrustManagers

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory getTrustManagers.

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

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 {//w  w w  . j av a2  s .c  o  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:com.clustercontrol.plugin.impl.WebServicePlugin.java

/**
 * ???WebService?Agent????????/*w  w w  . j a v a  2s  .c  om*/
 * @param addressPrefix ? http://x.x.x.x:xxxx? ?
 * @param addressBody ??? addressPrefix ??
 * @param endpointInstance
 * @param threadPool ?
 */
protected void publish(String addressPrefix, String addressBody, Object endpointInstance,
        ThreadPoolExecutor threadPool) {

    try {
        final URL urlPrefix = new URL(addressPrefix);
        final String fulladdress = addressPrefix + addressBody;
        HttpsServer httpsServer = null;
        // ? HTTPS???????HttpsService???endpoit.publish?????
        // URL??????????HttpsService?????Hashmap???????HashMap?
        // HTTPSServer???????????
        if ("https".equals(urlPrefix.getProtocol())) {
            httpsServer = httpsServerMap.get(addressPrefix);
            if (httpsServer == null) {
                // HTTPS Server??HTTPS?????????????????????
                String protocol = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.protocol", "TLS");
                String keystorePath = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.path",
                        HinemosPropertyDefault
                                .getString(HinemosPropertyDefault.StringKey.WS_HTTPS_KEYSTORE_PATH));
                String keystorePassword = HinemosPropertyUtil
                        .getHinemosPropertyStr("ws.https.keystore.password", "hinemos");
                String keystoreType = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.type",
                        "PKCS12");
                log.info("Starting HTTPS Server...");
                log.info("SSLContext: " + protocol + ", KeyStore: " + keystoreType);
                SSLContext ssl = SSLContext.getInstance(protocol);
                KeyManagerFactory keyFactory = KeyManagerFactory
                        .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                KeyStore store = KeyStore.getInstance(keystoreType);
                try (InputStream in = new FileInputStream(keystorePath)) {
                    store.load(in, keystorePassword.toCharArray());
                }
                keyFactory.init(store, keystorePassword.toCharArray());
                TrustManagerFactory trustFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustFactory.init(store);
                ssl.init(keyFactory.getKeyManagers(), trustFactory.getTrustManagers(), new SecureRandom());
                HttpsConfigurator configurator = new HttpsConfigurator(ssl);

                // ??HTTPSSever???Hashmap??
                httpsServer = HttpsServer
                        .create(new InetSocketAddress(urlPrefix.getHost(), urlPrefix.getPort()), 0);
                httpsServer.setHttpsConfigurator(configurator);
                httpsServerMap.put(addressPrefix, httpsServer);
            }
        }

        // ?????endpoint??
        log.info("publish " + fulladdress);
        final Endpoint endpoint = Endpoint.create(endpointInstance);
        endpoint.setExecutor(threadPool);
        if (httpsServer != null) {
            endpoint.publish(httpsServer.createContext(addressBody));
        } else {
            endpoint.publish(fulladdress);
        }
        endpointList.add(endpoint);
    } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException
            | IOException | CertificateException | RuntimeException e) {
        log.warn("failed to publish : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
    } finally {

    }
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public ConnectionHandler() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, KeyManagementException {

    InputStream keyStoreStream = getClass().getResourceAsStream("/web/module/resources/truststore.jks");

    // Load the keyStore
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
    keyStoreStream.close();//from  ww  w  .j  av a2 s. c  o m

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();
    setImplementationId();
}

From source file:at.diamonddogs.net.SSLHelper.java

/**
 * Register a keystore with SSL (JAVA)/*  w  w w .  ja  va 2  s .com*/
 * 
 * @param c
 *            a {@link Context}
 * @param resourceId
 *            the resource id of the keystore
 * @param password
 *            the password of the keystore
 * @return true on success, false otherwise
 */
public boolean initSSLFactoryJava(Context c, int resourceId, String password) {
    try {
        if (c == null || resourceId == -1 || password == null) {
            LOGGER.info("No keystore specified, using alltrust");
            makeAllTrustManagerForJava();
            return true;
        } else {
            KeyStore store = getKeyStore(c, resourceId, password);
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(store);
            SSLContext sslCtx = SSLContext.getInstance("TLS");
            sslCtx.init(null, tmf.getTrustManagers(), null);
            SSL_FACTORY_JAVA = sslCtx.getSocketFactory();
            sslState.trustAll = false;
            return true;
        }
    } catch (Throwable tr) {
        LOGGER.warn("Error initializing SSLFactoryJava", tr);
        try {
            makeAllTrustManagerForJava();
            sslState.tr = tr;
            return true;
        } catch (Throwable tr1) {
            sslState.tr1 = tr1;
            sslState.sslOk = false;
            LOGGER.warn("Error trusting all certs, no ssl connection possible", tr);
        }
        return false;
    }
}

From source file:org.elasticsearch.xpack.ssl.SSLClientAuthTests.java

private SSLContext getSSLContext() {
    try (InputStream in = Files.newInputStream(
            getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.jks"))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(in, "testclient".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);/*  ww w.  j  a va2 s  . c  o m*/
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "testclient".toCharArray());
        SSLContext context = SSLContext.getInstance("TLSv1.2");
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return context;
    } catch (Exception e) {
        throw new ElasticsearchException("failed to initialize a TrustManagerFactory", e);
    }
}

From source file:org.cloudcoder.submitsvc.oop.builder.WebappSocketFactory.java

private SSLSocketFactory createSocketFactory() throws IOException, GeneralSecurityException {
    String keyStoreType = "JKS";
    InputStream keyStoreInputStream = this.getClass().getClassLoader().getResourceAsStream(keystoreFilename);
    if (keyStoreInputStream == null) {
        throw new IOException("Could not load keystore " + keystoreFilename);
    }//from w  ww .j a  v a 2  s . c om

    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreInputStream, keystorePassword.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyStoreInputStream);
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    //trustManagerFactory.init(trustStore);
    // XXX Load the cert (public key) here instead of the private key?
    trustManagerFactory.init(keyStore);

    // TrustManager
    X509TrustManager x509TrustManager = null;
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            x509TrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
    if (x509TrustManager == null) {
        throw new IllegalArgumentException("Cannot find x509TrustManager");
    }

    // KeyManager
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
    X509KeyManager x509KeyManager = null;
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            x509KeyManager = (X509KeyManager) keyManager;
            break;
        }
    }
    if (x509KeyManager == null) {
        throw new NullPointerException();
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { x509KeyManager }, new TrustManager[] { x509TrustManager }, null);

    return sslContext.getSocketFactory();
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

private IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(this.keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    idmClient.setToken(restAccessToken);
    return idmClient;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

private VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(this.keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    VmdirClient vmdirClient = new VmdirClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    vmdirClient.setToken(restAccessToken);
    return vmdirClient;
}

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 {/*  w  w w  . ja v  a  2 s .  c  o  m*/
            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:org.fabric3.admin.interpreter.communication.DomainConnectionImpl.java

private void setSocketFactory(HttpsURLConnection connection) throws CommunicationException {
    try {/*from  ww  w . j a va2 s.  c o m*/
        if (sslFactory == null) {
            // initialize the SSL context
            String keyStoreLocation = getKeystoreLocation();
            if (keyStoreLocation == null) {
                throw new CommunicationException(
                        "Keystore not configured. A keystore must be placed in /config when using SSL.");
            }
            System.setProperty(KEY_STORE, keyStoreLocation);
            System.setProperty(TRUST_STORE, keyStoreLocation);
            KeyStore keyStore = KeyStore.getInstance("JKS");
            InputStream stream = new FileInputStream(keyStoreLocation);
            keyStore.load(stream, null);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tmf.getTrustManagers(), null);
            sslFactory = ctx.getSocketFactory();
        }
        connection.setSSLSocketFactory(sslFactory);
    } catch (NoSuchAlgorithmException | CertificateException | KeyManagementException | KeyStoreException
            | IOException e) {
        throw new CommunicationException(e);
    }
}