I am trying to override the trust manager in Android. I want to let the underlying trust manager check certificates but I need to determine if a certificate is expired. If t
If you never initialise the origTrustmanager
instance variable, it will have its default value of null
, which will indeed cause an NPE any time you're trying to use it.
I've just edited my previous answer on this to show an example of TrustManager initialisation. (I haven't tried on Android, but it works fine in plain Java.)
Be careful not to catch too much. Here, you're catching CertificateException
and Exception
in your trust manager: this is as good as having nothing, since these methods are meant to throw those exceptions. Make sure you only catch CertificateExpiredException
if you want to ignore expiration dates.
Note that this is only a trick that relies on the fact that, in practice, the certificate verification is done after the general trust verification (at least in the OpenJDK implementation). As far as I know, there's nothing in the specifications that says that the certificate expiration is verified after. It was done before other verification on elements of trust and you ignored that exception, you could let more certificate through than you want.
Use this code This is working for me
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { tm }, null);
} catch (Exception e1) {
e1.printStackTrace();
return;
}
AsyncSSLSocketMiddleware sslMiddleWare = Ion.getDefault(context).getHttpClient().getSSLSocketMiddleware();
sslMiddleWare.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
sslMiddleWare.setSSLContext(sslContext);
Ion.getDefault(context).getHttpClient().getSSLSocketMiddleware().setTrustManagers(trustAllCerts);
Ion.getDefault(context).getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
Ion.with(context).load("POST", serverUrl)
.setHeader("Content-Type", "application/json")
.setHeader("Accept", "application/json")
.setLogging("ION_LOGGING", Log.VERBOSE).setJsonObjectBody(json)