Example usage for javax.net.ssl SSLContext setDefault

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

Introduction

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

Prototype

public static void setDefault(SSLContext context) 

Source Link

Document

Sets the default SSL context.

Usage

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

public String getHttpBody(String url, String method, List<NameValuePair> param) {
    HttpClient httpClient = null;/*from  w  ww.  j  a  va 2  s. c om*/
    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;
}

From source file:org.wso2.carbon.identity.provisioning.connector.InweboUserManager.java

/**
 * Set the client certificate to Default SSL Context
 *
 * @param certificateFile File containing certificate (PKCS12 format)
 * @param certPassword    Password of certificate
 * @throws Exception/*  w  w w. ja  va  2 s.co m*/
 */
public static void setHttpsClientCert(String certificateFile, String certPassword)
        throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException,
        UnrecoverableKeyException, KeyManagementException, IdentityProvisioningException {
    if (certificateFile == null || !new File(certificateFile).exists()) {
        throw new IdentityProvisioningException("The certificate file is not found");
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    InputStream keyInput = new FileInputStream(certificateFile);
    keyStore.load(keyInput, certPassword.toCharArray());
    keyInput.close();
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
    SSLContext.setDefault(context);
}

From source file:sample.tomcat.X509ApplicationTests.java

@After
public void reset() throws Exception {
    SSLContext.setDefault(this.defaultContext);
}

From source file:com.daoke.mobileserver.test.TestHttps.java

public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
        throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;/*w w  w . ja v  a  2s.  co m*/
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

public void testBuilderUsesDefaultSSLContext() throws Exception {
    final SSLContext defaultSSLContext = SSLContext.getDefault();
    try {//from w  ww. j  a  v a 2s .  com
        try (RestClient client = buildRestClient()) {
            try {
                client.performRequest("GET", "/");
                fail("connection should have been rejected due to SSL handshake");
            } catch (Exception e) {
                assertThat(e.getMessage(), containsString("General SSLEngine problem"));
            }
        }

        SSLContext.setDefault(getSslContext());
        try (RestClient client = buildRestClient()) {
            Response response = client.performRequest("GET", "/");
            assertEquals(200, response.getStatusLine().getStatusCode());
        }
    } finally {
        SSLContext.setDefault(defaultSSLContext);
    }
}

From source file:org.picketlink.test.integration.federation.saml.SAMLIDPInitiatedSSLAuthenticationTestCase.java

@Test
@OperateOnDeployment("identity-provider")
public void testIdPInitiatedSSO() throws Exception {
    KeyStore keyStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.keystore", "PKCS12");
    KeyStore trustStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.truststore",
            KeyStore.getDefaultType());

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .loadKeyMaterial(keyStore, "change_it".toCharArray()).build();

    SSLContext.setDefault(sslcontext);

    WebRequest request = new GetMethodWebRequest("https://localhost:8443/idp-ssl");

    WebConversation conversation = new WebConversation();

    WebResponse response = conversation.getResponse(request);

    assertTrue(response.getText().contains("SAML 2.0 IdP-Initiated SSO"));
}

From source file:org.picketlink.test.integration.federation.saml.SAMLSPInitiatedFallbackFormSSLAuthenticationTestCase.java

@Test
@OperateOnDeployment("service-provider")
public void testSPInitiatedSSOWithoutClientCert() throws Exception {
    KeyStore trustStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.truststore",
            KeyStore.getDefaultType());

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();/*ww w .  j a va2 s.c  o m*/

    SSLContext.setDefault(sslcontext);

    WebRequest request = new GetMethodWebRequest("https://localhost:8443/sales-post-ssl");

    WebConversation conversation = new WebConversation();

    conversation.setExceptionsThrownOnErrorStatus(false);

    WebResponse response = conversation.getResponse(request);

    assertEquals("https://localhost:8443/idp-ssl/", response.getURL().toString());

    assertTrue(response.getText().contains("login_form"));
}

From source file:org.picketlink.test.integration.federation.saml.SAMLSPInitiatedSSLAuthenticationTestCase.java

@Test
@OperateOnDeployment("service-provider")
public void testSPInitiatedSSO() throws Exception {
    KeyStore keyStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.keystore", "PKCS12");
    KeyStore trustStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.truststore",
            KeyStore.getDefaultType());

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .loadKeyMaterial(keyStore, "change_it".toCharArray()).build();

    SSLContext.setDefault(sslcontext);

    WebRequest request = new GetMethodWebRequest("https://localhost:8443/sales-post-ssl");

    WebConversation conversation = new WebConversation();

    WebResponse response = conversation.getResponse(request);

    assertTrue(response.getText().contains("Welcome to the Sales Tool"));
}

From source file:io.specto.hoverfly.junit.HoverflyRuleUtils.java

static void setHoverflyTrustStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException, URISyntaxException {
    // load your key store as a stream and initialize a KeyStore
    InputStream trustStream = findResourceOnClasspath("hoverfly.jks").toURL().openStream();

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    // load the stream to your store
    trustStore.load(trustStream, "hoverfly".toCharArray());

    // initialize a trust manager factory with the trusted store
    TrustManagerFactory trustFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init(trustStore);/*from   ww w  .  ja  va2 s  .com*/

    // get the trust managers from the factory
    TrustManager[] trustManagers = trustFactory.getTrustManagers();

    // initialize an ssl context to use these managers and set as default
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagers, null);
    SSLContext.setDefault(sslContext);
}