How can I reduce the waiting time for ssl handshake?

Jury A picture Jury A · Jul 19, 2012 · Viewed 7.3k times · Source

I have the following code from http://sanjaal.com/java/tag/get-public-key-of-ssl-certificate-in-java/ that creates a socket and initiate ssl handshake.

SSLSocketFactory factory = HttpsURLConnection
.getDefaultSSLSocketFactory();

System.out.println("Creating a SSL Socket For "+hostname+" on port "+port);

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

socket.startHandshake();
System.out.println("Handshaking Complete");

The problem is that if the handshake could not establish, there is a long waiting time before I see the exception: Connection timed out

How can I set a maximum waiting time ? and what is the suitable minimum amount of time that ensures me that ssl handshake is not going to be successful.

Answer

user207421 picture user207421 · Jul 19, 2012

'Connection timeout' has nothing to do with the handshake, or even SSL. It doesn't happen when you call startHandshake(): it happens when you create the socket. Your stack trace would have told you that.

To reduce it, create a Socket() using the default constructor; call connect(SocketAddress address, long timeout); then if that succeeds call SSLSocketFactory.createSocket(Socket, ...) to wrap it in an SSLSocket.

NB the blog you cited is very poor quality indeed. Some of the problems with it:

  1. An SSL certificate does not 'enable encryption'. It is there primarily for authentication. It also plays a minor, inessential role in the handshake leading to the session key.

  2. TLS offers a lot more than just 'prevent[ing] eavesdropping, tampering, and message forgery': it also prevents replay and man-in-the-middle attacks too, for example; and it offers many more encryption possibilities than just RSA with 1024 or 2048 byte keys.

  3. The suggestion that 'At the browser level, it only means that the browser has validated the server’s certificate', and that for security the user/application must 'cipher something using the public key contained in the certificate and assure that the server can understand it' is complete nonsense. The browser has already checked that the server owns that certificate, via the digital-signature mechanism, during the SSL handshake.

  4. All this: 'the “locked padlock” icon has no relationship to the URL, DNS name or IP address of the server – thinking otherwise is a common misconception. Such a binding can only be securely established if the URL, name or address is specified in the server’s certificate itself. ' is completely incorrect. HTTPS includes checking the hostname against what is embedded in the certificate: and what is embedded in the certificate is put there and checked by the signing authority.

Don't rely on unrefereed unreviewed sites like that. Use the official product documentation.