GVKun编程网logo

javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

30

本文将带您了解关于javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信

本文将带您了解关于javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚的新内容,另外,我们还将为您提供关于Android 2.3.x javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚、Android java.security.cert.CertPathValidatorException:找不到证书路径的信任锚、Android JavaMail应用程序-CertPathValidatorException:找不到证书路径的信任锚、Android KSOAP2 SSL java.security.cert.CertPathValidatorException的实用信息。

本文目录一览:

javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

我正在使用Retrofit来访问我的REST API.但是,当我把我的API放在ssl后面并通过http:// myhost / myapi访问它时,我收到此错误:

我的API落后于SSL,我是否需要做一些额外的事情?

这是我如何连接:

private final String API = "https://myhost/myapi";

private final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
        .setServer(API)
        .setLogLevel(RestAdapter.LogLevel.FULL)
        .build();

01-10 09:49:55.621    2076-2100/com.myapp.mobile D/Retrofit﹕ javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
            at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:401)
            at libcore.net.http.httpconnection.setupSecureSocket(httpconnection.java:209)
            at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
            at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
            at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
            at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
            at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
            at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:497)
            at libcore.net.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:134)
            at retrofit.client.UrlConnectionClient.readResponse(UrlConnectionClient.java:90)
            at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:48)
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:287)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:222)
            at $Proxy12.signin(Native Method)
            at com.myapp.loginactivity$3.doInBackground(LoginActivity.java:143)
            at com.myapp.loginactivity$3.doInBackground(LoginActivity.java:136)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
            at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:282)
            at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:202)
            at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:595)
            at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
            at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:398)
            at libcore.net.http.httpconnection.setupSecureSocket(httpconnection.java:209)
            at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
            at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
            at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
            at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
            at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
            at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:497)
            at libcore.net.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:134)
            at retrofit.client.UrlConnectionClient.readResponse(UrlConnectionClient.java:90)
            at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:48)
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:287)
            at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:222)
            at $Proxy12.signin(Native Method)
            at com.myapp.LoginActivity$3.doInBackground(LoginActivity.java:143)
            at com.myapp.LoginActivity$3.doInBackground(LoginActivity.java:136)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)

解决方法:

发生这种情况的原因是JVM / Dalvik对系统或用户证书存储中的CA证书没有信心.

要使用Retrofit修复此问题,如果使用okhttp,则使用其他客户端非常相似.
你要这样做:

一种).创建包含CA的公钥的证书库.为此,您需要为* nix启动下一个脚本.
你需要在你的机器上安装openssl,并从https://www.bouncycastle.org/下载jar bcprov-jdk16-1.46.jar.不下载此版本
另外,1.5x版本与android 4.0.4不兼容.

#!/bin/bash

if [ -z $1 ]; then
  echo "Usage: cert2Android<CA cert PEM file>"
  exit 1
fi

CACERT=$1
BCJAR=bcprov-jdk16-1.46.jar

TRUSTSTORE=mytruststore.bks
ALIAS=`openssl x509 -inform PEM -subject_hash -noout -in $CACERT`

if [ -f $TRUSTSTORE ]; then
    rm $TRUSTSTORE || exit 1
fi

echo "Adding certificate to $TRUSTSTORE..."
keytool -import -v -trustcacerts -alias $ALIAS \
      -file $CACERT \
      -keystore $TRUSTSTORE -storetype BKS \
      -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider \
      -providerpath $BCJAR \
      -storepass secret

echo "" 
echo "Added '$CACERT' with alias '$ALIAS' to $TRUSTSTORE..."

B).将文件truststore mytruststore.bks复制到项目的res / raw中

C).设置连接的SSLContext:

.............
okHttpClient = new OkHttpClient();
try {
    KeyStore ksTrust = KeyStore.getInstance("BKS");
    InputStream instream = context.getResources().openRawResource(R.raw.mytruststore);
    ksTrust.load(instream, "secret".tochararray());

    // TrustManager decides which certificate authorities to use.
    TrustManagerFactory tmf = TrustManagerFactory
        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ksTrust);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {
    e.printstacktrace();
}
.................

Android 2.3.x javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

Android 2.3.x javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

我只在(可能是一些)2.3.x设备上收到此错误.它适用于运行 Android版本的任何其他设备.

这是我的HTTPRequestController:

public class HttpRequestController {

private final static String TAG = "HttpRequestController";

private static HttpRequestController instance;

public enum Method {
    PUT,POST,DELETE,GET
}

private HttpRequestController() {

}

public static HttpRequestController getInstance() {
    if (instance == null)
        instance = new HttpRequestController();

    return instance;
}

public String doRequest(String url,HashMap<Object,Object> data,Method method,String token) throws Exception {

    InputStream certificateInputStream = null;
    if (MyApplication.PRODUCTION) {
        certificateInputStream = MyApplication.context
                .getResources().openRawResource(R.raw.production_cert);
        LogUtils.log("using production SSL certificate");
    } else {
        certificateInputStream = MyApplication.context
                .getResources().openRawResource(R.raw.staging_cert);
        LogUtils.log("using staging SSL certificate");
    }

    KeyStore trustStore = KeyStore.getInstance("BKS");
    try{
    trustStore.load(certificateInputStream,"re3d6Exe5HBsdskad8efj8CxZwv".tochararray());
    } finally {
        certificateInputStream.close();
    }


    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    LogUtils.log("SSL: did init TrustManagerFactory with trust keyStore");
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null,tmf.getTrustManagers(),null);
    LogUtils.log("SSL: did init context with trust keyStore");  


    URL request = new URL(url);
    HttpsURLConnection urlConnection = (HttpsURLConnection) request
            .openConnection();

    LogUtils.log("SSL: did open HttpsURLConnection");   

    urlConnection.setHostnameVerifier(new StrictHostnameVerifier());
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setConnectTimeout(15000);
    LogUtils.log("SSL: did set Factory and Timeout.");

    if (method != Method.GET){
        urlConnection.setDoOutput(true);
    }
        urlConnection.setDoInput(true);
        urlConnection.setRequestProperty("Content-Type","application/json");
        urlConnection.setRequestProperty("Accept","application/json");

    LogUtils.log("SSL: urlConnection did set request properties.");

    if (token != null) {
        urlConnection.setRequestProperty("Authorization","Token " + token);
    }
        urlConnection.setRequestMethod(method.toString());
        urlConnection.connect();

        LogUtils.log("SSL: urlConnection did connect.");

    if (method != Method.GET) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonValue = mapper.writeValueAsstring(data);
        OutputStream os = urlConnection.getoutputStream();
        os.write(jsonValue.getBytes());
        os.flush();
        LogUtils.log(TAG,"Params: " + jsonValue);
    }

    LogUtils.log(TAG,method.toString() + ": " + url);

    InputStream in = null;
    if (urlConnection.getResponseCode() == 200) {
        in = urlConnection.getInputStream();
    } else {
        in = urlConnection.getErrorStream();
    }
    String response = convertStreamToString(in);

    LogUtils.log(TAG,"Got response : " + url);
    LogUtils.log(TAG,"Response : " + response);

    return response;
}

public String convertStreamToString(InputStream inputStream) {
    BufferedReader buffReader = new BufferedReader(new InputStreamReader(
            inputStream));
    StringBuilder stringBuilder = new StringBuilder();

    String line = null;
    try {
        while ((line = buffReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
    } catch (IOException e) {
        e.printstacktrace();
    } finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printstacktrace();
        }
    }
    return stringBuilder.toString();
}

public HttpClient retrieveHttpClient() {
    return new MyHttpClient(MyApplication.context);
}

}

当我运行命令时:

openssl s_client -debug -connect www.mysitedomain.com:443

我收到了回复:

--
some key stuff 
--
Certificate chain
 0 s:/OU=Domain Control Validated/CN=www.mydomainname.com
   i:/C=BE/O=GlobalSign nv-sa/CN=GlobalSign Domain Validation CA - G2
 1 s:/C=BE/O=GlobalSign nv-sa/CN=GlobalSign Domain Validation CA - G2
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
 2 s:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
---
Server certificate
-----BEGIN CERTIFICATE-----
 some more certificate stuff
-----END CERTIFICATE-----

ubject=/OU=Domain Control Validated/CN=www.mydomainname.com
issuer=/C=BE/O=GlobalSign nv-sa/CN=GlobalSign Domain Validation CA - G2
---
No client certificate CA names sent
---
SSL handshake has read 4091 bytes and written 328 bytes
---
New,TLSv1/SSLv3,Cipher is DHE-RSA-AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : DHE-RSA-AES256-SHA
    Session-ID: 57C379C59483809A7FE1BF8E235C5BFA7789E62AAEBCA9BC14B5273F5D1304E7
    Session-ID-ctx: 
    Master-Key: 6FCD498D1294415A42B57420F0C05AB903EF8E56CB6F1530390F73AF5E4CBC22B359D5CDA09811E075A5C598002C380D
    Key-Arg   : None
    Start Time: 1390473282
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

所以它返回没问题…但它仍然给我测试的2.3.x设备的这个错误.

在此之后我得到一个例外:

LogUtils.log("SSL: urlConnection did set request properties.");

这是例外:

01-23 10:20:28.459: W/System.err(1623): javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:477)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:328)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.http.httpconnection.setupSecureSocket(httpconnection.java:185)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:433)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.makeConnection(HttpsURLConnectionImpl.java:378)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
01-23 10:20:28.459: W/System.err(1623):     at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:152)

我称之为的方式是:

String response = HttpRequestController
                            .getInstance()
                            .doRequest(ApiUrls.LOGIN,params,Method.POST,null);

它适用于运行2.3.x以上Android版本的任何其他设备(根据我的测试).

Android文档似乎没有关于2.3兼容性的主题.

解决方法

您必须告诉Android系统信任您的证书.您的问题是2.3之后的Android接受了您的证书,因为它包含在可信证书列表中,但是之前的版本不包括在内,因此,存在问题.

我建议你在Android文档上做:

// Load CAs from an InputStream
// (Could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
    ca = cf.generateCertificate(caInput);
    System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} 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,null);

// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://certs.cac.washington.edu/CAtest/");
HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in,System.out);

我也在做同样的事情,它在每台设备上运行正常,使用Android 2.3及以下版本,我的网站证书是私有的.

试试吧,告诉我它现在是否正常工作.

希望它能帮到你!

Android java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

Android java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

android应用有三台主机进行身份验证和授权。最终主机是REST API。首次使用Oauth身份验证和授权过程,它可以正常工作。

但是,如果 用户 在登录并访问REST API提供的服务后 杀死了该应用程序 ,然后再次打开该应用程序,则会出现此问题。
在这段时间内,身份验证和授权过程不会发生,只有REST API会发生。
这是造成原因,java.security.cert.CertPathValidatorException
但在首次使用(登录然后使用该应用程序)期间正在工作。

有人可以解释此异常背后的情况以及该应用程序有什么问题。如果根据此SO答案将认证异常忽略如下,则此方法有效。

SSLSocketFactory sslSocketFactory = null;

        try {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            // Initialise the TMF as you normally would,for example:
            try {
                tmf.init((KeyStore)null);
            } catch(KeyStoreException e) {
                e.printStackTrace();
            }
            TrustManager[] trustManagers = tmf.getTrustManagers();

            final X509TrustManager origTrustmanager = (X509TrustManager)trustManagers[0];

            // Create a trust manager that does not validate certificate chains
            TrustManager[] wrappedTrustManagers = new TrustManager[]{
                    new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return origTrustmanager.getAcceptedIssuers();
                        }

                        public void checkClientTrusted(X509Certificate[] certs,String authType) {
                            try {
                                origTrustmanager.checkClientTrusted(certs,authType);
                            } catch(CertificateException e) {
                                e.printStackTrace();
                            }
                        }

                        public void checkServerTrusted(X509Certificate[] certs,String authType) {
                            try {
                                origTrustmanager.checkServerTrusted(certs,authType);
                            } catch(CertificateException e) {
                                e.printStackTrace();
                            }
                        }
                    }
            };
            //TrustManager[] trustAllCerts = TrustManagerFactory.getInstance("SSL").getTrustManagers();

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null,wrappedTrustManagers,new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        return sslSocketFactory;

我对http请求使用Okhttp 3。任何建议都将有助于解决问题。并且请告诉我是否使用上述代码段,是否违反安全规定?对应用程序的安全性有影响吗?

Android JavaMail应用程序-CertPathValidatorException:找不到证书路径的信任锚

Android JavaMail应用程序-CertPathValidatorException:找不到证书路径的信任锚

请在重复之前,请先阅读我的问题.
使用自签名证书时,我已阅读有关此错误的许多问题和解答.但是,我的问题是,尝试连接到GMAIL imap服务器时出现此错误.所以,我真的需要一些帮助.我的代码是:

private String[] ReadMailBox(String MailBoxName) throws IOException {
    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imaps.port", "993");
    List<String> FromAddressArrList = new ArrayList<String>();

    props.setProperty("mail.store.protocol", "imaps");
    try {
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect("imap.gmail.com", "username", "password");
        ActiveMailBox = store.getFolder(MailBoxName);
        ActiveMailBox.open(Folder.READ_ONLY);
        Message[] messages = ActiveMailBox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            Message message = messages[i];
            Address[] from = message.getFrom();
            FromAddressArrList.add(from[0].toString());
        }
        //ActiveMailBox.close(true);
        store.close();
    } catch (NoSuchProviderException e) {
        FromAddressArrList.add(e.toString());
    } catch (MessagingException e) {
        FromAddressArrList.add(e.toString());
    }
    String[] FromAddressArr = new String[FromAddressArrList.size()];
    FromAddressArrList.toArray(FromAddressArr);
    return FromAddressArr;
}

我收到此错误消息:

javax.mail.MessagingException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.; nested exception is: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

现在,当涉及到自签名证书时,我会发生这种情况,但是为什么在尝试连接到GMAIL时收到此消息?您能帮我使我的应用程序正常工作吗?

解决方法:

可能有防火墙,防病毒或代理程序正在拦截您连接到邮件服务器的请求,并提供其证书而不是Gmail证书.使用InstallCert程序查看它要提供给您的证书.

另一种可能性是信任库为空,丢失或配置不正确,这就是为什么它找不到信任锚的原因.

Android KSOAP2 SSL java.security.cert.CertPathValidatorException

Android KSOAP2 SSL java.security.cert.CertPathValidatorException

我尝试通过SSL连接到我的JAX-WS服务.没有SSL一切正常.

AsyncTask中的方法:

     HttpsTransportSE  androidHttpTransport = new HttpsTransportSE("10.0.2.2", 8181, "/Server/?wsdl", 10000);
             ((HttpsServiceConnectionSE) androidHttpTransport.getServiceConnection()).setSSLSocketFactory(trustAllHosts()
.getSocketFactory());

             //androidHttpTransport.debug=true;

             androidHttpTransport.call(getSoapAction(method), envelope);

获取SSLContext

public SSLContext allowAllSSL() {
            SSLContext context = null; 
            TrustManager[] trustManagers = null;
            try{
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

             KeyStore keyStore = KeyStore.getInstance("pkcs12");
             InputStream in = cntx.getResources().openRawResource(R.raw.client_keystore);
             try {
             keyStore.load(in, "password".tochararray());
             } catch (CertificateException e) {
             // Todo Auto-generated catch block
             e.printstacktrace();
             } finally {
             in.close();
             }
             tmf.init(keyStore);


                if (trustManagers == null) { 
                        trustManagers = new TrustManager[] { new Fakex509trustmanager() }; 
                } 

                try { 
                        context = SSLContext.getInstance("SSL"); 
                        context.init(null, tmf.getTrustManagers(), new SecureRandom()); 
                } catch (NoSuchAlgorithmException e) { 
                        e.printstacktrace(); 
                } catch (KeyManagementException e) { 
                        e.printstacktrace(); 
                } 

           HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
           HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
               public boolean verify(String hostname, SSLSession session) {
                    return true;
                  }
                });
            }catch(Exception ex)
            {
                Log.e(TAG,"allowAllSSL Failed: "+ex.toString());
            }
           return context;
        } 

我收到此错误日志:

12-18 07:51:42.161: E/Example:logonAsync(3161): doInBackground Failed: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
12-18 07:51:42.161: W/System.err(3161): javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
12-18 07:51:42.169: W/System.err(3161):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:401)
12-18 07:51:42.169: W/System.err(3161):     at libcore.net.http.httpconnection.setupSecureSocket(httpconnection.java:209)
12-18 07:51:42.169: W/System.err(3161):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
12-18 07:51:42.169: W/System.err(3161):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)

解决方法:

我发现问我的问题:在MainAsync中:

 HttpsTransportSE  androidHttpTransport = new HttpsTransportSE(10.0.2.2, 8181, "/server/?wsdl", 10000);
             ((HttpsServiceConnectionSE) androidHttpTransport.getServiceConnection()).setSSLSocketFactory(trustAllHosts().getSocketFactory());


protected  SSLContext trustAllHosts()
{   
    return allowAllSSL();
}

 public SSLContext allowAllSSL() {
        SSLContext context = null; 
        TrustManager[] trustManagers = null;
        KeyManagerFactory mgrFact;
        try{
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        mgrFact = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

         KeyStore keyStore = KeyStore.getInstance("pkcs12");
         InputStream in = cntx.getResources().openRawResource(R.raw.keystore);
         try {
         keyStore.load(in, "password".tochararray());
         mgrFact.init(keyStore, "password".tochararray());
         } catch (CertificateException e) {
         // Todo Auto-generated catch block
         e.printstacktrace();
         } finally {
         in.close();
         }
         tmf.init(keyStore);


            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() 
            {    
                    @Override 
                    public boolean verify(String hostname, SSLSession session) { 

                            return true; 
                    } 

            }); 


            if (trustManagers == null) { 
                    trustManagers = new TrustManager[] { new Fakex509trustmanager() }; 
            }

            final TrustManager[] trustAllCerts = new TrustManager[] {new x509trustmanager() {
                public X509Certificate[] getAcceptedissuers() {
                    System.out.println("getAcceptedissuers");
                     return null;
                }
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    System.out.println("Сведения о сертификате : " +       chain[0].getIssuerX500Principal().getName() + "\n Тип авторизации : " + authType);
                }
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    System.out.println("checkClientTrusted : " + authType);
                }
            } };
            //tmf.getTrustManagers()
            try { 
                    context = SSLContext.getInstance("TLS"); 
                    context.init(mgrFact.getKeyManagers(), trustAllCerts, new SecureRandom()); 
            } catch (NoSuchAlgorithmException e) { 
                    e.printstacktrace(); 
            } catch (KeyManagementException e) { 
                    e.printstacktrace(); 
            } 

       HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
       HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
           public boolean verify(String hostname, SSLSession session) {
                return true;
              }
            });
        }catch(Exception ex)
        {
            Log.e(TAG,"allowAllSSL Failed: "+ex.toString());
        }
       return context;
    } 

今天关于javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚的分享就到这里,希望大家有所收获,若想了解更多关于Android 2.3.x javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚、Android java.security.cert.CertPathValidatorException:找不到证书路径的信任锚、Android JavaMail应用程序-CertPathValidatorException:找不到证书路径的信任锚、Android KSOAP2 SSL java.security.cert.CertPathValidatorException等相关知识,可以在本站进行查询。

本文标签: