Ady Wicaksono Daily Activities

SSL Connection with Java

with one comment

Here is an example Java code to create SSL connection between you and HTTPS
(taken from http://www.cafeaulait.org/slides/iw2000/whatsnew/04.html)

import java.net.*;
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class HTTPSClient {
	public static void main(String[] args) {
		if (args.length == 0) {
			System.out.println("Usage: java HTTPSClient host");
			return;
		}

		int port = 443; // default https port
		String host = args[0];

		try{
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

			SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

			Writer out = new OutputStreamWriter(socket.getOutputStream());
			// https requires the full URL in the GET line
			out.write("GET / HTTP/1.0\\r\\\n");
			out.write("\\r\\n");
			out.flush();

			// read response
			BufferedReader in = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
			int c;
			while ((c = in.read()) != -1) {
				System.out.write(c);
			}

			out.close();
			in.close();
			socket.close();
		}catch (IOException e) {
			System.err.println(e);
		}
	}
}

You can compile & run it:

$ javac HTTPSClient.java
$ java HTTPSClient login.yahoo.com

But wait, if HTTPS server give you certificate which is signed by “unknown” Certificate Authority ( I mean not signed by approved CA like Thawte, Verisign) then you will get this error

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

or something like it

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found

However, I found the fast solutions (I forget where was it, but I started from Google)
so all certificates (signed and unsigned) become accepted and the exception disappears.
Of course this is not recommended for a production system but quite useful for testing :).

import java.net.*;
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class HTTPSClient {
	public static void main(String[] args) {
		if (args.length == 0) {
		   System.out.println("Usage: java HTTPSClient host");
		   return;
		}

		int port = 443; // default https port
		String host = args[0];

		
		TrustManager[] trustAll = new javax.net.ssl.TrustManager[]{
		  new javax.net.ssl.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 {
		
			javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
			sc.init(null, trustAll, new java.security.SecureRandom());
		
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			SSLSocketFactory factory = (SSLSocketFactory) sc.getSocketFactory();
			SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

			Writer out = new OutputStreamWriter(socket.getOutputStream());
			out.write("GET / HTTP/1.0\\r\\n");
			out.write("\\r\\n");
			out.flush();

			// read response
			BufferedReader in = new BufferedReader(
			new InputStreamReader(socket.getInputStream()));
			int c;
			while ((c = in.read()) != -1) {
				System.out.write(c);
			}
			out.close();
			in.close();
			socket.close();
		}catch (Exception e) {
			System.err.println(e);
		}
	}
}
About these ads

Written by adywicaksono

July 15, 2007 at 4:20 pm

One Response

Subscribe to comments with RSS.

  1. i want a sample code to establish connection between client and server using ssl protocol

    manoj

    March 24, 2011 at 5:55 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: