If you want to dynamically import a certificate, you may need to use x509TrustManager . This is done when configuring SSLContext , which itself is used to create an SSLSocketFactory or SSLEngine .
jSSLutils is a library that allows you to wrap existing trust managers and configure specific parameters. You do not need it, but it can help.
This will go along these lines:
PKIXSSLContextFactory sslContextFactory = new PKIXSSLContextFactory(); sslContextFactory.setTrustManagerWrapper(new X509TrustManagerWrapper() { @Override public X509TrustManager wrapTrustManager(final X509TrustManager origManager) { return new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return origManager.getAcceptedIssuers(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try {
( (PKIX)SSLContextFactory and X509TrustManagerWrapper come from jSSLutils, but the rest are available with J2SE / J2EE.)
There are several CertificateException s that you might want to catch (see subclasses). If you are making a callback for the user, it is possible that the SSL / TLS connection will not be completed the first time due to a timeout in the SSL / TLS handshake (if the callback takes too long to get a response.)
Then you can use this SSLContext as your default using SSLContext.setSSLContext(...) (from Java 6), but this is not necessarily a good idea. If you can, pass SSLContext to the library that makes the SSL / TLS connection. How this is done changes, but Apache HTTP Client 4.x, for example, has several options for setting its SSL settings, one of which is KeyStore s transfer, the other is SSLContext transfer.
You can also use something in the stream instead of a single object that will connect (depending on the library) by checking the current stream in x509TrustManager : this would probably make things a little more complicated in terms of synchronization and flow control / awareness trustee.
Bruno
source share