信任锚未获得认证路径的异常

时间:2016-02-19 23:07:43

标签: android tomcat exception ssl https

您好我正在尝试使用https

在tomcat服务器和Android应用程序之间建立ssl通信

1-我使用keytool为tomcat创建密钥库文件

2-然后生成一个pem文件,将其与keytool一起使用以生成BKS文件

3- tomcat服务器工作正常

基本上我遵循了这篇文章

问题是当我尝试使用HttpsURLConnection从Android应用程序连接时,我总是得到异常:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:351)
at com.android.okhttp.Connection.upgradeToTls(Connection.java:1323)
at com.android.okhttp.Connection.connect(Connection.java:1225)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:395)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:221)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
at org.apache.cordova.rest.Rest.send(Rest.java:177)

帮助!!

2 个答案:

答案 0 :(得分:0)

两种可能的解决方案

1)如果您使用自签名证书,请尝试将证书(.crt / .cer)添加到信任库。

2)如果您的证书由本地CA签名,请确保将根CA和中间CA导入信任库。

答案 1 :(得分:0)

            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = getApplicationContext().getResources()
                    .openRawResource(R.raw.my_certificate);//new BufferedInputStream(is);
            Certificate ca;
            try {
                ca = cf.generateCertificate(caInput);
            } finally {
                caInput.close();
            }

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

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

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

最后将sslcontext设置为HttpsURLConnection