[Q] Random SSLHandshakeException

Search This thread

Auroratic

Member
Jun 15, 2013
48
0
Austria
Hallo,
I have the following function in my AsyncTask:
Code:
private SSLContext trustCert() throws Exception {
        SSLContext context = null;

        context = SSLContext.getInstance("TLS");

        // Load CAs from an InputStream
        // (could be from a resource or ByteArrayInputStream or ...)
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = this.context.getResources().openRawResource(R.raw.cert);
        Certificate ca = cf.generateCertificate(caInput);
        caInput.close();

        // Create a KeyStore containing our trusted CAs
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

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

        // Create an SSLContext that uses our TrustManager
        context.init(null, tmf.getTrustManagers(), null);
        return context;
    }

In the doInBackground-Function im loading some resources from my server with a self-signed certificate:
Code:
SSLContext sslContext = this.trustCert();
        HttpsURLConnection conn = (HttpsURLConnection) address.openConnection();
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
......
 conn.connect(); //here i get the error

And sometimes (!) I get following Error on the last line of the code posted:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

But why?
 

TheDoubleTap

Member
Jan 16, 2014
14
1
Hi

Are you sure your sever is well configured ? It seems that there are some intermediate certificates missing from the certificate chain but google "Trust anchor not found" you'll find some helpful links :)
 

zxgangandy

New member
Jan 24, 2014
1
0
Hi

Are you sure your sever is well configured ? It seems that there are some intermediate certificates missing from the certificate chain but google "Trust anchor not found" you'll find some helpful links :)


I have met this issue before. My solution is setting the verifier host and ssl factory before you setting up the https utl connection


e.g. :

private static void trustAllHosts() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(notVerify);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
}

add this method before your https connection create method. Hope it can help you.