views:

291

answers:

1

I'm currently having a self signed certificate for my HTTPS webserver.

In my java program there is a SSLSocketFactory that will create a socket to the webserver. The default implementation of sun blocks the self signed certificate. With an own implementation of a X509TrustManager I can only check whether the date of the certificate is valid.

Is there any possibility to let the default implementation check the validity (date and hostname, ...), and if it fails to show a dialog to let the user accept this certificate?

Each code I found until now only disabled the ssl check and accepted every invalid certificate.

+1  A: 

I haven't actually tried this, but why can't you implement your own trust manager, which first delegates to the default trust manager to check if the certificate is valid and if not, asks the user if he still wants to accept the certificate?


You can initialize most of the security classes with null arguments to use default values. To obtain the default trust manager, you must get the available trust managers and choose the first one in the mgrs arrays to implement the X509TrustManager interface. Usually, the array will only contain one elment anyway.

TrustManagerFactory trustmanagerfactory = 
     TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustmanagerfactory.init((KeyStore)null);
TrustManager[] mgrs = trustmanagerfactory.getTrustManagers();

After you've wrapped the default trust manager with your own extension, you have to initialize an SSL context and get a socket factory from it:

SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null, new TrustManager[] {myTm}, null);
SSLSocketFactory sf = sslContext.getSocketFactory();

Then use this socket factory to create new client sockets or pass it to HttpsURLConnection.setDefaultSSLSocketFactory to use the https protocol in URLs with your own trust manager.

jarnbjo
I had the same idea, but faced many problems while trying to get and use the existing trust manager (needs keystore and more instances for init). Most of the SUN classes are internal, final or the jdk does not contain the source codes.Maybe you have any solution?
André
Thx for the fast reply. I will try this again this weekend. Maybe there was a little mistake in my code :SNext comment will contain my result.
André
hi again. I don't now, what I did wrong before :) Retrieving the first default trust manager with your code above, fetching the exceptions of them and throw them when the user declines it works fine. thx
André