gpt4 book ai didi

android - 如何在 Android 的 SSLSocketFactory 中添加信任库?

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:37 25 4
gpt4 key购买 nike


我正在编写一个带有 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();

关于android - 如何在 Android 的 SSLSocketFactory 中添加信任库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40082689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com