我开始遵循一个不在
Android环境中的教程,并得出以下结论:
System.setProperty("javax.net.ssl.trustStore","truststore"); System.setProperty("javax.net.ssl.trustStorePassword","password"); SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); try { Socket s = ssf.createSocket("192.168.2.11",6543); PrintWriter out = new PrintWriter(s.getOutputStream()); while (true){ out.println("SSL TEST"); Log.d("DATA","DATA SENT"); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
我想这可以归结为几个问题:
>我没有创建自己的信任商店,但是在线搜索教程和内容,我不知道如何创建一个.有没有办法创建或修改信托商店以获得我需要的证书? (如果有任何差异,我正在使用自签名证书)
>如何使SSL握手顺利运行?现在,我得到的错误是:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
解决方法
1)这取决于您是否在服务器端具有自签名证书,并且您尝试验证您的身份到Android设备?或者您是否在Android端尝试验证您的idendity到服务器?如果是前者,那么请看这个链接:
http://www.codeproject.com/KB/android/SSLVerification_Android.aspx?display=Mobile
您要特别注意KeyStore文件的位置.
2)您收到该错误的原因是因为您不信任您正在连接的服务器,因为您没有正确创建信任库,或者您正在连接到其证书尚未添加到信任库的服务器.你到底要连接什么?
3)确保你有< uses-permission android:name =“android.permission.INTERNET”/>在manifest.xml中.
编辑
我的道歉请看我对第一段的修改.
这是初始化您的密钥库和信任库的部分
SSLcontext sslContext = SSLContext.getDefault(); KeyStore trustSt = KeyStore.getInstance("BKS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); InputStream trustStoreStream = this.getResources().openRawResource(R.raw.truststore); trustSt.load(trustStoreStream,"<yourpassword>".tocharArray()); trustManagerFactory.init(trustStre); KeyStore keyStore = KeyStore.getInstance("BKS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); InputStream keyStoreStream = this.getResources().openRawResource(R.raw.keystore); keyStore.load(keyStoreStream,"<yourpassword>".tocharArray()); keyManagerFactory.init(keyStore,"<yourpassword>".tocharArray()); sslContext.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),null);