Search code examples
androidhttpsssl-certificateandroid-7.0-nougatnetwork-security

SSL handshake exception while connecting over https using self signed certificate in android Nougat


In my android application i connect over https. I am using a self signed certificate to connect. It is working on devices below api level 24 (before android nougat).But on android Nougat it throws the SSL Handshake exception :

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

This is how i connect over https:-

SSLContext context = null;
    try 
    {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream input = new BufferedInputStream(context.getAssets().open(pkcsFilename));
        try {
            // Initialize the keystore with the provided trusted certificates
            // Also provide the password of the keystore
            keyStore.load(input, password.toCharArray());
        } finally {
            input.close();
        }

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, "".toCharArray());

        // Load CAs from an InputStream
        // (could be from a resource or ByteArrayInputStream or ...)
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate ca = null;
        input = new BufferedInputStream(context.getAssets().open(certificateFilename));
        try 
        {
            ca = cf.generateCertificate(input);
        }
        finally
        {
            input.close();
        }
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("server", ca);

        // Create a TrustManager that trusts the CAs in our KeyStore
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager
        context = SSLContext.getInstance("TLS");
        context.init(keyFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();

I tried the following link, But it does not help.

This is my network config file. I have added it in my AndroidManifest.xml file.

    <?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">xyz.com</domain>
        <trust-anchors>
        <certificates src="@raw/root_ca" />
        </trust-anchors>
    </domain-config>
</network-security-config>

Please help me how to solve this .


Solution

  • i got it working by adding a custom trust managers. While initializing the SSL Context context.init(keyFactory.getKeyManagers(), tmf.getTrustManagers(), null);

    I modified it as :
    
    context.init(keyFactory.getKeyManagers(), new TrustManager[] { tm }, null);
    TrustManager tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }
    
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        for (int j=0; j<chain.length; j++)
                        {
                            chain[j].checkValidity();
                            try {
                                chain[j].verify(ca.getPublicKey());
                            } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException |
                                    SignatureException e) {
                                e.printStackTrace();
                                throw new CertificateException(e.getMessage());
                            }
                        }
                    }
    
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
    

    i verify the certificate with the server certificate . Now its working .