Java: how to show a dialog allowing the user to accept SSL certificates

I currently have my own certificate for my HTTPS web server.

My java program has an SSLSocketFactory that will create a socket for the web server. By default, the sun implementation blocks a self-signed certificate. With my own implementation of X509TrustManager, I can only check the validity of the certificate.

Is it possible to allow the default implementation to verify the correctness (date and hostname, ...), and if it fails to show a dialog to allow the user to accept this certificate?

Each code that I have found so far has only disabled ssl verification and accepted every invalid certificate.

+4
source share
1 answer

I have not 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 wants to accept the certificate yet?


You can initialize most security classes with null arguments to use the default values. To get the default trust manager, you must get the available trust managers and select the first of the mgrs arrays to implement the X509TrustManager interface. Typically, an array will contain only one eluent.

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

After you wrapped the default trust manager with your own extension, you should initialize the SSL context and get the factory socket from it:

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

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

+1
source

All Articles