gpt4 book ai didi

使用自签名证书和 CA 的 Android SSL HTTP 请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:25 29 4
gpt4 key购买 nike

我有一个连接到我们托管的 SSL Web 服务的 Android 应用程序。 Web 服务器是 apache,有我们​​自己创建的 CA 和自签名的 SSL 证书。

我已将我们的 CA 证书导入到 Android 平板电脑的安全性用户信任证书部分。

我已经测试了对网络服务器的访问,并且可以确认网络服务证书显示为有效(下面的屏幕截图)

Valid certificate

这是安全设置中的证书:

Trusted certificate

现在,当我尝试访问我的应用程序中的网络服务时,我会触发“无对等证书”异常。

这是简化的 SSL 实现:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// allows network on main thread (temp hack)
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

SchemeRegistry schemeRegistry = new SchemeRegistry();
//schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
schemeRegistry.register(new Scheme("https", newSSLSocketFactory(), 443));


HttpParams params = new BasicHttpParams();

SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry);

HttpClient client = new DefaultHttpClient(mgr, params);

HttpPost httpRequest = new HttpPost("https://our-web-service.com");

try {
client.execute(httpRequest);
} catch (Exception e) {
e.printStackTrace(); //
}
}

/*
* Standard SSL CA Store Setup //
*/
private SSLSocketFactory newSSLSocketFactory() {

KeyStore trusted;

try {
trusted = KeyStore.getInstance("AndroidCAStore");
trusted.load(null, null);
Enumeration<String> aliases = trusted.aliases();

while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
X509Certificate cert = (X509Certificate) trusted.getCertificate(alias);
Log.d("", "Alias="+alias);
Log.d("", "Subject DN: " + cert.getSubjectDN().getName());
Log.d("", "Issuer DN: " + cert.getIssuerDN().getName());
}

SSLSocketFactory sf = new SSLSocketFactory(trusted);
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

return sf;

} catch (Exception e) {
// TODO Auto-generated catch block
throw new AssertionError(e);
}
}

}

while 循环只是吐出证书,我可以在日志中看到我自己的 CA。但我仍然得到“无对等证书”异常。

10-17 18:29:01.234: I/System.out(4006): 没有对等证书

我是否必须在此实现中以某种方式手动加载我的 CA 证书?

最佳答案

通过使用解决:HttpsURLConnection

URLConnection conn = null;
URL url = new URL(strURL);
conn = url.openConnection();
HttpsURLConnection httpsConn = (HttpsURLConnection) conn;

这似乎适用于用户安装的 CA 证书。

关于使用自签名证书和 CA 的 Android SSL HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433058/

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