我正在编写一个带有 SSL 连接(不是 HTTP)的 Android 应用程序。我在 Android 中阅读了很多关于 HTTPS 的教程,但它保持产品错误“SSL socket factory is abstract cannot be instantiated”。使用 SSLSocketFactory sf = new SSLSocketFactory(truststore)
。
我的问题是:如何将 key 存储添加到 Android?
这是我的例子:
public void run() {
try {
KeyStore trusted = KeyStore.getInstance("BKS");
InputStream in = context.getResources().openRawResource(R.raw.keystore);
try {
trusted.load(in, "1234567".toCharArray());
SSLSocketFactory sSLSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); // <<<<< Line 40
SSLSocket sslSocket = (SSLSocket) sSLSocketFactory.createSocket("10.0.2.2", 9998);
sslSocket.startHandshake();
Log.i("SSLsocket", "true");
} finally {
in.close();
}
} catch (Exception e) {
throw new AssertionError(e);
}
}
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:322)
at com.example.begood.voip.SSlconnection.run(SSlconnection.java:40)
尝试这样的事情,给定你的 trustStore:
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(trustStore, "password".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
TrustManagerFactory tmf=TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
SSLContext sslContext=SSLContext.getInstance("TLSv1.2");
sslContext.init(keymanagers, tmf.getTrustManagers(), new SecureRandom());
SSLSocketFactory factory=sslContext.getSocketFactory();
我是一名优秀的程序员,十分优秀!