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:com.upyun.sdk.utils.HttpClientUtils.java

@SuppressWarnings("deprecation")
public static HttpClient getInstance() {
    HttpClient client = new DefaultHttpClient();
    SSLContext ctx = null;
    try {//from  ww  w . j av a2 s  . c  o  m
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
    } catch (Exception e) {
        LogUtil.exception(logger, e);
    }
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = client.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    client = new DefaultHttpClient(ccm, client.getParams());
    return client;
}

From source file:com.scsy150.util.OtherUtils.java

public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override//from w  ww .j  av a  2s  .  c  om
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Throwable e) {
            LogUtil.e("", e.getMessage());
        }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
}

From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static SSLContext getSSLContext(VaultProperties.Ssl ssl) throws GeneralSecurityException, IOException {

    KeyManager[] keyManagers = ssl.getKeyStore() != null
            ? createKeyManagerFactory(ssl.getKeyStore(), ssl.getKeyStorePassword()).getKeyManagers()
            : null;//from   w  w w .j  a v  a2  s  .c  om

    TrustManager[] trustManagers = ssl.getTrustStore() != null
            ? createTrustManagerFactory(ssl.getTrustStore(), ssl.getTrustStorePassword()).getTrustManagers()
            : null;

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);

    return sslContext;
}

From source file:org.qi4j.library.http.AbstractSecureJettyTest.java

@BeforeClass
public static void beforeSecureClass() throws IOException, GeneralSecurityException {
    defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        public boolean verify(String string, SSLSession ssls) {
            return true;
        }/*from  w ww. j  a  v a  2s. c  om*/

    });
    KeyStore truststore = KeyStore.getInstance("JCEKS");
    truststore.load(new FileInputStream(TRUSTSTORE_FILE), KS_PASSWORD.toCharArray());
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance(getX509Algorithm());
    caTrustManagerFactory.init(truststore);
    sslCtx.init(null, caTrustManagerFactory.getTrustManagers(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
}

From source file:it_minds.dk.eindberetningmobil_android.server.DebugOkHttpStack.java

private static OkHttpClient getUnsafeOkHttpClient(OkHttpClient client) {
    try {/*from w w w.  j  a v a 2s .com*/
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        client.setSslSocketFactory(sslSocketFactory);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:utils.TestUtils.java

@SuppressWarnings("deprecation") // http api
public static CloseableHttpClient createHttpsClient() {
    try {//  w  ww . j a  v  a  2s. c o  m
        TrustManager[] trustAllCerts = new TrustManager[] { new NonValidatingX509TrustManager() };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[] {}, trustAllCerts, null);
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 443, socketFactory);
        CloseableHttpClient http = new DefaultHttpClient();
        http.getConnectionManager().getSchemeRegistry().register(sch);
        return http;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java

public static boolean checkHttpsURLStatus(final String url) {
    boolean https_StatusFlag = false;
    System.out.println("Entered in checkHttpsURLStatus >>>>>>>>>>>>>>>");

    URL httpsurl;/*from   ww w .ja va  2 s .c  o m*/
    try {

        // Create a context that doesn't check certificates.
        SSLContext ssl_ctx = SSLContext.getInstance("TLS");
        TrustManager[] trust_mgr = get_trust_mgr();
        ssl_ctx.init(null, // key manager
                trust_mgr, // trust manager
                new SecureRandom()); // random number generator
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());
        System.out.println("Url =========" + url);
        httpsurl = new URL(url);

        HttpsURLConnection con = (HttpsURLConnection) httpsurl.openConnection();
        con.setHostnameVerifier(DO_NOT_VERIFY);
        int statusCode = con.getResponseCode();
        System.out.println("statusCode =========" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK) {

            https_StatusFlag = true;

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return https_StatusFlag;
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout,
        int readTimeout) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;// w w w.ja  va2 s . co m
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            //SSLContext.setDefault(ctx);
            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setSSLSocketFactory(ctx.getSocketFactory());

            conn.setRequestProperty("Cookie", cookieStr);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            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:com.adguard.compiler.Main.java

/**
 * Disable SSL validation (it may work wrong sometimes)
 *
 * @throws NoSuchAlgorithmException//www . j  a v a2 s  .  c  o m
 * @throws KeyManagementException
 */
private static void disableSslValidation() throws NoSuchAlgorithmException, KeyManagementException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

private static URL waitForDependency(URL url, String serviceName, String key, String value, String username,
        String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;/*from   w  ww. j a  v  a  2 s. co m*/
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + url.getPath());
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH,
                                TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH,
                                CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    log.info(username + ":******");
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")"
                                + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")"
                            + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}