Example usage for javax.net.ssl SSLContext init

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

Introduction

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

Prototype

public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException 

Source Link

Document

Initializes this context.

Usage

From source file:org.obiba.mica.core.service.AgateRestService.java

/**
 * Do not check anything from the remote host (Agate server is trusted).
 *
 * @return/* w  w  w.  ja v a2 s  .  com*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private SSLConnectionSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    // Accepts any SSL certificate
    TrustManager tm = new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { tm }, null);

    return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule.java

@Singleton
@Provides//from   w w w  . j a  v  a  2 s  . c  om
final SSLContext newSSLContext(HttpUtils utils,
        @Named("untrusted") Supplier<SSLContext> untrustedSSLContextProvider)
        throws NoSuchAlgorithmException, KeyManagementException {
    if (utils.trustAllCerts())
        return untrustedSSLContextProvider.get();
    SSLContext context = SSLContext.getInstance("TLS");

    context.init(null, null, null);
    return context;
}

From source file:com.nesscomputing.tinyhttp.HttpFetcher.java

public HttpFetcher(final SSLConfig sslConfig) {
    params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    registry.register(HTTP_SCHEME);//from w w  w.  j av  a  2  s  .  c  om

    if (sslConfig != null && sslConfig.isSSLEnabled()) {
        try {
            final TrustManager[] trustManagers = new TrustManager[] {
                    HttpsTrustManagerFactory.getTrustManager(sslConfig) };
            final SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, null);
            final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
                    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            registry.register(new Scheme("https", 443, sslSocketFactory));
            LOG.debug("HTTPS enabled.");
        } catch (GeneralSecurityException ce) {
            throw Throwables.propagate(ce);
        } catch (IOException ioe) {
            throw Throwables.propagate(ioe);
        }
    } else {
        LOG.debug("HTTPS disabled.");
    }

    connectionManager = new SingleClientConnManager(registry);

    LOG.debug("HTTP fetcher ready.");
}

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

public PollingSslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {//from  w w w  .j  ava2s  . c  o m
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            keyStore.load(new FileInputStream(System.getProperty(KEY_STORE)), password);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize keystore", e); //$NON-NLS-1$
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize SSL context", e); //$NON-NLS-1$
    }
}

From source file:co.cask.cdap.security.server.ExternalMTLSAuthenticationServerTestBase.java

private HttpClient getHTTPClient(KeyManager[] kms, TrustManager[] tms) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(kms, tms, new SecureRandom());
    // only for test purposes ignoring check of certificate hostname matching host on which server runs
    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", getAuthServerPort(), sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    // Apache HttpClient version >4.2 should use BasicClientConnectionManager
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    return new DefaultHttpClient(cm);
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Same as buildContext(), but wraps all X509TrustManagers in a SavableTrustManager to provide
 * UntrustedCertificateExceptions so that when a client connects to a server it does not trust,
 * the program can recover the key and ask the user if they wish to trust it.
 *
 * @param trustMaterial/*from w  w  w  .j a v  a 2s . c om*/
 * @return
 */
public static SSLContext buildClientContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);
        ctx = SSLContext.getInstance("TLS");
        //key manager factory go!
        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        TrustManager[] trustManagers = tmf.getTrustManagers();

        for (int i = 0; i < trustManagers.length; i++) {
            if (trustManagers[i] instanceof X509TrustManager) {
                System.out.println("Wrapped a trust manager.");
                trustManagers[i] = new SavableTrustManager((X509TrustManager) trustManagers[i]);
            }
        }

        ctx.init(keyMgr.getKeyManagers(), trustManagers, null);
    } catch (KeyStoreException | UnrecoverableKeyException | KeyManagementException
            | NoSuchAlgorithmException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ctx = null;
    }

    return ctx;
}

From source file:org.vsearchd.crawler.backend.BackendSessionHTTPS.java

private Scheme getHttpSslTheme(String url) throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, getTrustManager(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    SSLSocketFactory socketFactory = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return new Scheme("https", Integer.valueOf(this.getBackendServer().getPort()), socketFactory);
}

From source file:io.getlime.push.configuration.PowerAuthWebServiceConfiguration.java

/**
 * Prepare a correctly configured PowerAuthServiceClient instance with the service
 * URL specified using 'powerauth.service.url' server property.
 *
 * @param marshaller JAXB marshaller/*from www.  j av  a 2  s  .c  om*/
 * @return Correctly configured PowerAuthServiceClient instance with the service
 * URL specified using 'powerauth.service.url' server property
 */
@Bean
public PowerAuthServiceClient powerAuthClient(Jaxb2Marshaller marshaller) {
    PowerAuthServiceClient client = new PowerAuthServiceClient();
    client.setDefaultUri(powerAuthServiceUrl);
    client.setMarshaller(marshaller);
    client.setUnmarshaller(marshaller);

    // if invalid SSL certificates should be accepted
    if (acceptInvalidSslCertificate) {

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

        } };

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            // ... ignore
        }

    }

    // if there is a configuration with security credentials, add interceptor
    if (!clientToken.isEmpty()) {
        ClientInterceptor[] interceptors = new ClientInterceptor[] { securityInterceptor() };
        client.setInterceptors(interceptors);
    }
    return client;
}

From source file:com.terradue.warhol.auth.ssl.SslAuthenticationConfiguration.java

@Override
public void configure(Builder httpClientConfig, SslAuthentication authentication) {
    // client//from  w w w .  j a  v  a 2  s  . com
    KeyManager[] keyManagers;
    if (authentication.getProxyCertificate() != null) {
        keyManagers = fromSslProxy(authentication.getProxyCertificate());
    } else if (authentication.getPublicCertificate() != null && authentication.getPrivateKey() != null) {
        keyManagers = fromSslKeyAndCertificate(authentication.getPublicCertificate(),
                authentication.getPrivateKey(), authentication.getPassword());
    } else {
        keyManagers = new KeyManager[] {};
    }

    // server
    TrustManager[] trustManagers;
    if (authentication.isCheckCertificate()) {
        trustManagers = new TrustManager[] {};
    } else {
        trustManagers = new TrustManager[] { new RelaxedTrustManager() };
    }

    SSLContext context = null;
    try {
        context = SSLContext.getInstance("TLS");
        context.init(keyManagers, trustManagers, null);
        httpClientConfig.setSSLContext(context);
    } catch (Exception e) {
        throw new IllegalStateException("Impossible to initialize SSL context", e);
    }
}

From source file:com.naver.timetable.bo.HttpClientBO.java

public String getHttpBody(String url, String method, List<NameValuePair> param) {
    HttpClient httpClient = null;//  w w  w  .j  a v a2s .  c o  m
    HttpResponse httpResponse = null;
    HttpRequestBase httpRequest;

    try {
        if (StringUtils.upperCase(method).equals("POST")) {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(param));
        } else {
            httpRequest = new HttpGet(url);
        }

        TrustManager[] trustManagers = new TrustManager[1];
        trustManagers[0] = new DefaultTrustManager();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
        SSLContext.setDefault(sslContext);

        sslContext.init(null, trustManagers, null);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        //         httpClient = HttpClientBuilder.create().build();
        httpResponse = httpClient.execute(httpRequest);
        return EntityUtils.toString(httpResponse.getEntity());
    } catch (ClientProtocolException e) {
        LOG.error("Client protocol error : ", e);
    } catch (IOException e) {
        LOG.error("IO error : ", e);
    } catch (KeyManagementException e) {
        LOG.error("IO error : ", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("IO error : ", e);
    } finally {
        // ?
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }

    return null;
}