Example usage for javax.net.ssl TrustManagerFactory init

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

Introduction

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

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:org.globus.gsi.jsse.SSLConfigurator.java

private void configureContext() throws GlobusSSLConfigurationException {

    ManagerFactoryParameters parameters = getCertPathParameters();
    TrustManager[] trustManagers;
    try {/*from  ww  w  . j  a v  a2  s .c om*/
        TrustManagerFactory fact = TrustManagerFactory.getInstance("GSI");
        fact.init(parameters);
        trustManagers = fact.getTrustManagers();
    } catch (NoSuchAlgorithmException e1) {
        throw new GlobusSSLConfigurationException(e1);
    } catch (InvalidAlgorithmParameterException e) {
        throw new GlobusSSLConfigurationException(e);
    }

    KeyManager[] keyManagers = loadKeyManagers();

    SecureRandom secureRandom = loadSecureRandom();

    sslContext = loadSSLContext();

    try {
        sslContext.init(keyManagers, trustManagers, secureRandom);
    } catch (KeyManagementException e) {
        throw new GlobusSSLConfigurationException(e);
    }

}

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  w  w w . ja  v  a  2s . c om*/
            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.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java

private SSLContext buildSslContext(SSLContextService sslService) throws IOException, CertificateException,
        NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance(sslService.getKeyStoreType());
    KeyStore trustStore = KeyStore.getInstance("JKS");

    try (final InputStream is = new FileInputStream(sslService.getKeyStoreFile())) {
        keyStore.load(is, sslService.getKeyStorePassword().toCharArray());
    }//from  w  w w  .  ja v a 2 s  .c o m

    try (final InputStream is = new FileInputStream(sslService.getTrustStoreFile())) {
        trustStore.load(is, sslService.getTrustStorePassword().toCharArray());
    }

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, sslService.getKeyStorePassword().toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    SSLContext context1 = SSLContext.getInstance(sslService.getSslAlgorithm());
    context1.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return context1;
}

From source file:com.clustercontrol.plugin.impl.WebServicePlugin.java

/**
 * ???WebService?Agent????????/* www.ja  v  a  2  s  .  c  o  m*/
 * @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:com.ibm.iotf.client.AbstractClient.java

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();/*w  w w  . ja  va 2  s  .  co  m*/
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    if (tmf != null) {
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        context.init(kmf.getKeyManagers(), null, null);
    }

    return context.getSocketFactory();
}

From source file:org.fabric3.admin.interpreter.communication.DomainConnectionImpl.java

private void setSocketFactory(HttpsURLConnection connection) throws CommunicationException {
    try {/* ww w  .ja  va 2s .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);
    }
}

From source file:info.guardianproject.cacert.CustomTrust.java

public CustomTrust(Context context, int rawResource, String password) throws IOException, KeyStoreException,
        KeyManagementException, NoSuchAlgorithmException, CertificateException {

    // Setup the SSL context to use the truststore
    ssl_ctx = SSLContext.getInstance("TLS");

    // Setup truststore
    KeyStore ksCACert = KeyStore.getInstance("BKS");
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    InputStream trustStoreStream = context.getResources().openRawResource(rawResource);
    ksCACert.load(trustStoreStream, password.toCharArray());

    //init factory with custom cacert
    trustManagerFactory.init(ksCACert);
    Log.d("SSL", "CACerts " + ksCACert.size());
    Log.d("SSL", "trustManagerFactory " + trustManagerFactory.getTrustManagers().length);

    // Setup client keystore
    /*/*from  w w w  .j  av a  2  s  .  c  om*/
    KeyStore keyStore = KeyStore.getInstance("BKS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    InputStream keyStoreStream = context.getResources().openRawResource(R.raw.clientkeystore);
    keyStore.load(keyStoreStream, "testtest".toCharArray());
    keyManagerFactory.init(keyStore, "testtest".toCharArray());
    Log.d("SSL", "Key " + keyStore.size());
            
    Log.d("SSL", "keyManagerFactory " + keyManagerFactory.getKeyManagers().length);
    */

    //nothing implemented yet
    SecureRandom secRand = SecureRandom.getInstance(RANDOM_ALGORITHM);

    ssl_ctx.init(null, trustManagerFactory.getTrustManagers(), secRand);

    socketFactory = (SSLSocketFactory) ssl_ctx.getSocketFactory();

}

From source file:com.alliander.osgp.shared.usermanagement.AuthenticationClient.java

/**
 * Construct an AuthenticationClient instance.
 *
 * @param keystoreLocation//ww  w  .j a  v  a  2 s  . c o m
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the AuthenticationClient.
 *
 * @throws AuthenticationClientException
 *             In case the construction fails, an
 *             AuthenticationClientException will be thrown.
 */
public AuthenticationClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws AuthenticationClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers, true);
        if (this.webClient == null) {
            throw new AuthenticationClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());

        this.jacksonObjectMapper = new ObjectMapper();
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:sabina.integration.TestScenario.java

/**
 * Convenience method to use own truststore on SSL Sockets. Will default to
 * the self signed keystore provided in resources, but will respect
 * <p>//from   w w  w  .j  a  v a 2  s. c  o m
 * -Djavax.net.ssl.keyStore=serverKeys
 * -Djavax.net.ssl.keyStorePassword=password
 * -Djavax.net.ssl.trustStore=serverTrust
 * -Djavax.net.ssl.trustStorePassword=password SSLApplication
 * <p>
 * So these can be used to specify other key/trust stores if required.
 *
 * @return an SSL Socket Factory using either provided keystore OR the
 * keystore specified in JVM params
 */
private SSLSocketFactory getSslFactory() {
    KeyStore keyStore;

    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream fis = new FileInputStream(getTrustStoreLocation());
        keyStore.load(fis, getTrustStorePassword().toCharArray());
        fis.close();

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:android.net.http.CertificateChainValidator.java

/**
 * Creates a new certificate chain validator. This is a pivate constructor.
 * If you need a Certificate chain validator, call getInstance().
 *///from ww  w.  j a  v a  2  s.  c  o m
private CertificateChainValidator() {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers != null && trustManagers.length > 0) {
            for (TrustManager trustManager : trustManagers) {
                if (trustManager instanceof X509TrustManager) {
                    mDefaultTrustManager = (X509TrustManager) (trustManager);
                    break;
                }
            }
        }
    } catch (Exception exc) {
        if (HttpLog.LOGV) {
            HttpLog.v("CertificateChainValidator():" + " failed to initialize the trust manager");
        }
    }
}