Creating an SSL Client Socket

When an SSL client socket connects to an SSL server, it receives a certificate of authentication from the server. The client socket then validates the certificate against a set of certificates in its \meta{trust store}.

The default truststore is <java-home>/lib/security/cacerts. If the server's certificate cannot be validated with the certificates in the truststore, the server's certificate must be added to the truststore before the connection can be established.

try { int port = 443; String hostname = "hostname"; SocketFactory socketFactory = SSLSocketFactory.getDefault(); Socket socket = socketFactory.createSocket(hostname, port); // Create streams to securely send and receive data to the server InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); // Read from in and write to out... // Close the socket in.close(); out.close(); } catch(IOException e) { }

A different truststore can be specified using the javax.net.ssl.trustStore system property. (If you are trying to set up an SSL client and server for testing purposes, you can set the truststore to the keystore that was created in Creating an SSL Server Socket.)

> java -Djavax.net.ssl.trustStore=truststore -Djavax.net.ssl.trustStorePassword=123456 MyApp

Comments

30 Jan 2010 - 3:00am by Anonymous (not verified)

understandable

2 Feb 2010 - 3:58am by Fábio (not verified)

Hi,

You explanation is very easy to understand, but after I implemented it, I had an error that I cant find either a solution or an explanation.

Can you help?

Thanks in advance.

(My objective is to read the content of the .js file)
Error:
java.net.UnknownHostException: https://192.168.0.10/sys/GetLoginData.js
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketFactoryImpl.createSocket(Unknown Source)
at testJavascrip.main(testJavascrip.java:61)

20 Feb 2010 - 3:30am by Sigma (not verified)

Fábio : you have to connect to 192.168.0.10, not to the URL. I think there are java classes made to connect directly to https websites.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.