Search in sources :

Example 71 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project xDrip by NightscoutFoundation.

the class ShareRest method getOkHttpClient.

private synchronized OkHttpClient getOkHttpClient() {
    try {
        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 null;
            }
        } };
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.networkInterceptors().add(new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                try {
                    // Add user-agent and relevant headers.
                    Request original = chain.request();
                    Request copy = original.newBuilder().build();
                    Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
                    Log.d(TAG, "Sending request: " + modifiedRequest.toString());
                    Buffer buffer = new Buffer();
                    copy.body().writeTo(buffer);
                    Log.d(TAG, "Request body: " + buffer.readUtf8());
                    final Response response = chain.proceed(modifiedRequest);
                    Log.d(TAG, "Received response: " + response.toString());
                    if (response.body() != null) {
                        MediaType contentType = response.body().contentType();
                        String bodyString = response.body().string();
                        Log.d(TAG, "Response body: " + bodyString);
                        return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
                    } else
                        return response;
                } catch (NullPointerException e) {
                    Log.e(TAG, "Got null pointer exception: " + e);
                    return null;
                } catch (IllegalStateException e) {
                    UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
                    return null;
                }
            }
        });
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException("Error occurred initializing OkHttp: ", e);
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) MediaType(com.squareup.okhttp.MediaType) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(com.squareup.okhttp.Interceptor) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) Response(com.squareup.okhttp.Response) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 72 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project xDrip-plus by jamorham.

the class ShareRest method getOkHttpClient.

private synchronized OkHttpClient getOkHttpClient() {
    try {
        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 null;
            }
        } };
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.networkInterceptors().add(new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                try {
                    // Add user-agent and relevant headers.
                    Request original = chain.request();
                    Request copy = original.newBuilder().build();
                    Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
                    Log.d(TAG, "Sending request: " + modifiedRequest.toString());
                    Buffer buffer = new Buffer();
                    copy.body().writeTo(buffer);
                    Log.d(TAG, "Request body: " + buffer.readUtf8());
                    final Response response = chain.proceed(modifiedRequest);
                    Log.d(TAG, "Received response: " + response.toString());
                    if (response.body() != null) {
                        MediaType contentType = response.body().contentType();
                        String bodyString = response.body().string();
                        Log.d(TAG, "Response body: " + bodyString);
                        return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
                    } else
                        return response;
                } catch (NullPointerException e) {
                    Log.e(TAG, "Got null pointer exception: " + e);
                    return null;
                } catch (IllegalStateException e) {
                    UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
                    return null;
                }
            }
        });
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException("Error occurred initializing OkHttp: ", e);
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) MediaType(com.squareup.okhttp.MediaType) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(com.squareup.okhttp.Interceptor) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) Response(com.squareup.okhttp.Response) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 73 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project keystore-explorer by kaikramer.

the class TimeStampingClient method queryServer.

/**
 * Get timestamp token (HTTP communication)
 *
 * @return TSA response, raw bytes (RFC 3161 encoded)
 * @throws IOException
 */
private static byte[] queryServer(String tsaUrl, byte[] requestBytes) throws IOException {
    // Install the all-trusting trust manager
    SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new X509TrustManager() {

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

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

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (KeyManagementException e) {
        throw new IOException(e);
    }
    SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    try {
        URL url = new URL(tsaUrl);
        URLConnection con = url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type", "application/timestamp-query");
        con.setRequestProperty("Content-Transfer-Encoding", "binary");
        OutputStream out = con.getOutputStream();
        out.write(requestBytes);
        out.close();
        InputStream is = con.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = is.read(buffer, 0, buffer.length)) >= 0) {
            baos.write(buffer, 0, bytesRead);
        }
        byte[] respBytes = baos.toByteArray();
        String encoding = con.getContentEncoding();
        if (encoding != null && encoding.equalsIgnoreCase("base64")) {
            respBytes = Base64.decode(new String(respBytes));
        }
        return respBytes;
    } finally {
        // restore default trust manager
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException) URL(java.net.URL) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 74 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project AndroidStudy by tinggengyan.

the class UnsafeOkHttpClient method getUnsafeOkHttpClient.

public static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // 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 null;
            }
        } };
        // 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();
        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient.Builder builder = okHttpClient.newBuilder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.protocols(Arrays.asList(Protocol.HTTP_1_1));
        builder.hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) CertificateException(java.security.cert.CertificateException) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 75 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project MtgDesktopCompanion by nicho92.

the class InstallCert method install.

public static void install(String website) throws IOException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    String host;
    int port;
    File defaultF = new File(System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security");
    char[] passphrase;
    String[] c = website.split(":");
    host = c[0];
    port = 443;
    passphrase = MTGConstants.KEYSTORE_PASS.toCharArray();
    File keystoreFile = new File(MTGConstants.CONF_DIR, MTGConstants.KEYSTORE_NAME);
    if (!keystoreFile.exists()) {
        boolean ret = keystoreFile.createNewFile();
        if (ret)
            FileUtils.copyFile(new File(defaultF, "cacerts"), keystoreFile);
        else
            throw new FileNotFoundException("Couldn't not create " + keystoreFile);
    }
    logger.debug("Loading KeyStore " + keystoreFile.getAbsolutePath() + "...");
    try (InputStream in = new FileInputStream(keystoreFile)) {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        logger.debug("Opening connection to " + host + ":" + port + "...");
        try (SSLSocket socket = (SSLSocket) factory.createSocket(host, port)) {
            socket.setSoTimeout(10000);
            logger.debug("Starting SSL handshake...");
            socket.startHandshake();
            logger.debug("No errors, certificate is already trusted");
            return;
        } catch (SSLException e) {
            logger.error(e);
        }
        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            logger.error("Could not obtain server certificate chain");
            return;
        }
        logger.debug("Server sent " + chain.length + " certificate(s):");
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        int i = 0;
        X509Certificate cert = chain[0];
        sha1.update(cert.getEncoded());
        md5.update(cert.getEncoded());
        String alias = host + "-" + (i++);
        ks.setCertificateEntry(alias, cert);
        OutputStream out = new FileOutputStream(new File(MTGConstants.CONF_DIR, MTGConstants.KEYSTORE_NAME));
        ks.store(out, passphrase);
        out.close();
        logger.debug("Added certificate to keystore '" + new File(MTGConstants.CONF_DIR, MTGConstants.KEYSTORE_NAME) + "' using alias '" + alias + "'");
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) SSLException(javax.net.ssl.SSLException) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) FileOutputStream(java.io.FileOutputStream) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) MessageDigest(java.security.MessageDigest) File(java.io.File)

Aggregations

SSLSocketFactory (javax.net.ssl.SSLSocketFactory)403 SSLContext (javax.net.ssl.SSLContext)150 SSLSocket (javax.net.ssl.SSLSocket)134 IOException (java.io.IOException)106 X509TrustManager (javax.net.ssl.X509TrustManager)69 Socket (java.net.Socket)63 TrustManager (javax.net.ssl.TrustManager)56 HostnameVerifier (javax.net.ssl.HostnameVerifier)49 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)48 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)48 Test (org.junit.Test)46 KeyManagementException (java.security.KeyManagementException)45 URL (java.net.URL)41 CertificateException (java.security.cert.CertificateException)39 OkHttpClient (okhttp3.OkHttpClient)39 OutputStream (java.io.OutputStream)35 InputStream (java.io.InputStream)34 X509Certificate (java.security.cert.X509Certificate)34 SSLSession (javax.net.ssl.SSLSession)30 InetSocketAddress (java.net.InetSocketAddress)29