insecurity_https_connection

Insecurity HTTPS Connection

The basic idea is to initial the SSLContext with a TrustManager that would never throw exception.

:!::!::!: This method is not secure, and can be attacked by Man-in-the-middle attack. THIS METHOD SHOULD NEVER USE IN PRODUCTION.:!::!::!: For production, consider using Adding crt to Java cacerts.

Do not say I did not warn you. A better method would be add the keystore to your Java trust store, which would not be show here.


Create a class with the following static methods. Note that only getContentFromURL() method is public, as I want to hide the other two methods from the others.

class HttpsTools {
    public static String getContentFromURL(String httpsURL) throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException {
        URL url;
        url = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        SSLContext ctx = SSLContext.getInstance("TLS");
        TrustManager[] trustManagers = HttpsTools.getTrustManagers;
        ctx.init(null, trustManagers, null);

        con.setSSLSocketFactory(ctx.getSocketFactory());
        con.setRequestMethod("GET");

        //dump all the content
        return getHttpContent(con);
    }

   private static String getHttpContent(HttpsURLConnection con) {
        StringBuilder sb = new StringBuilder();
        if (con != null) {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String input;
                while ((input = br.readLine()) != null) {
                    sb.append(input);
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    private static TrustManager[] getTrustManagers = new TrustManager[]{
			new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			}
		};
	}
}

To use it, import the above file to your java, and call:

String myString = HttpsTools.getContentFromURL("https://www.google.com")
  • insecurity_https_connection.txt
  • Last modified: 2018/10/03 09:23
  • by chongtin