Validating a Certificate on Android using platform CAs

This post is about using the Android platform provided trust store to validate an X509Certificate.

First, you need to get an instance of TrustManagerFactory.

String defAlgo=TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(defAlgo);

Then you need to initialise it. This can be done by calling

tmf.init((KeyStore) null); //use default platform set of trusted CAs

We pass in null to initialise it with the platform provided set of CAs.

Now, we have to iterate through the TrustManagers provided by the TrustManagerFactory and find the required type. After that you can call the checkServerTrusted method with the certificate chain.

TrustManager[] tms = tmf.getTrustManagers();
for(TrustManager tm : tms){
if(tm instanceof X509TrustManager){
((X509TrustManager) tm).checkServerTrusted(certs,"blah");
return true;// cert is trusted
}
}

The second param is the key exchange algorithm portion of the cipher suites and cannot be empty or null, so we can pass in a random string for this use case.

If the certificate chain is not trusted, the above code will throw an exception.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.