我正在尝试从我的 Android 应用程序连接到基于 node.js 的 TLS 服务器。自然会失败,因为我使用的是自签名证书。
无论如何我可以将证书添加到我的应用程序并让 Android 以某种方式信任它吗?注意,我没有使用 HTTPS,这是一个 TLS over TCP 连接。
最佳答案
经过大量阅读,我想出了一个答案。
这里有一个很好的指南:http://nelenkov.blogspot.no/2011/12/using-custom-certificate-trust-store-on.html
现在,由于我没有使用 HTTPS,我不得不想出一个稍微不同的方法来使用新的 keystore 获得干净的 SSL 套接字:
KeyStore store = KeyStore.getInstance("BKS");
InputStream truststore = mainActivity.getResources().openRawResource(R.raw.trust);
store.load(truststore, "PASSWORD".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(store);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), new SecureRandom());
Socket socket = context.getSocketFactory().createSocket(ip, port);
关于Android TLS 连接和自签名证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018681/