Creating Your Own X509TrustManager
If the supplied X509TrustManager
behavior isn't
suitable for your situation, you can create your own X509TrustManager
by
either creating and registering your own TrustManagerFactory
or
by implementing the X509TrustManager
interface directly.
The following
MyX509TrustManager
class enhances the default
IBMJSSE2
X509
TrustManager
behavior by providing alternative authentication logic when the
default IBMJSSE2
X509
TrustManager
fails.
class MyX509TrustManager implements X509TrustManager {
/*
* The default X509TrustManager returned by IbmX509. We'll delegate
* decisions to it, and fall back to the logic in this class if the
* default X509TrustManager doesn't trust it.
*/
X509TrustManager pkixTrustManager;
MyX509TrustManager() throws Exception {
// create a default JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("trustedCerts"), "passphrase".toCharArray());
TrustManagerFactory tmf =
TrustManagerFactory.getInstance("IbmX509", "IBMJSSE2");
tmf.init(ks);
TrustManager tms [] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look
* for an instance of X509TrustManager. If found,
* use that as our default trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
pkixTrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
pkixTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
// do any special handling here, or rethrow exception.
}
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
pkixTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the
* cert chain.
*/
}
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return pkixTrustManager.getAcceptedIssuers();
}
}
Once you have created such a trust manager, assign it to an
SSLContext
via the
init
method. Future SocketFactories
created from this
SSLContext
will use your new TrustManager
when making trust
decisions.
TrustManager[] myTMs = new TrustManager [] {
new MyX509TrustManager()
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, myTMs, null);
Accepting Anonymous Cipher Suites
You can enhance MyX509Trustmanager
to
accept anonymous cipher suites. Enhance checkServerTrusted
to
verify that it is appropriate to accept this anonymous cipher and
return. Your new TrustManager will now accept anonymous cipher suites.