Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix unsafe implementation of X509TrustManager in Android app

Tags:

Google has advised that I have an unsafe implementation of the interface X509TrustManager in my Android application and need to change my code as follows:

To properly handle SSL certificate validation, change your code in the checkServerTrusted method of your custom X509TrustManager interface to raise either CertificateException or IllegalArgumentException whenever the certificate presented by the server does not meet your expectations. For technical questions, you can post to Stack Overflow and use the tags “android-security” and “TrustManager.”

How can the following code be modified to fix the above issue?

public EasySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {     super(truststore);      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;         }     };      mContext.init(null, new TrustManager[] { tm }, null); } 
like image 791
Nabeel Avatar asked Feb 20 '16 23:02

Nabeel


2 Answers

I have solved this using the following code:

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {                 try {                     chain[0].checkValidity();                 } catch (Exception e) {                     throw new CertificateException("Certificate not valid or trusted.");                 }             } 
like image 71
Nabeel Avatar answered Sep 28 '22 08:09

Nabeel


If you encounter this from external library you're using, check if appache libraray is the cause of it.

For me apache library caused the error : i was using deprecated class - MultipartEntity. This class uses SSLContextBuilder which uses TrustManagerDelegate. TrustManagerDelegate implements X509TrustManager, which cause "unsafe implementation of TrustManager" error when uploading application to google play store.

The solution is : instead of deprecated MultipartEntity class, use MultipartEntityBuilder.

For example :

MultipartEntity httpMultipart = new MultipartEntity(); String contentType = httpMultipart.getContentType().getValue(); 

Will be replaced by :

MultipartEntityBuilder httpMultipart = new MultipartEntityBuilder(); String contentType = httpMultipart.build().getContentType().getValue(); 
like image 23
Dus Avatar answered Sep 28 '22 10:09

Dus