英文:
How to ADD self-signed certificates to default certificates in HttpsURLConnection
问题
早上好。
我的问题是,我想创建一个HttpsURLConnection
,它接受默认的受信任证书,还有我的自签名证书。
在互联网上搜索了一下,我找到了很多类似的问题,但并不完全是我想要的。
特别地,一个不错的代码在这里。
这基本上就是我想要的,但有一个区别:
他们只信任自签名证书,我也想信任自签名证书。
基本上,我不想从空的KeyStore
开始,我想获取默认的密钥库,不管它在哪里,只要它已经包含了我操作系统中的默认证书。
附注:我在Android上工作。
谢谢大家。
英文:
Good morning.
My problem is, I want to create a HttpsURLConnection
that accepts default trusted certificates but also my self-signed certificated.
After looking around in Internet, I found a lot of similar questions, but not exactly what I want.
In particular, a good code is here.
This is pretty much what I want, but with a difference:
They will trust ONLY the self-signed certificates, I want to trust ALSO the self-signed certificates.
Basically I don't want to start from an empty KeyStore
, I would like to get the default keystore, whatever/wherever it is, something that already contains the default certificates in my OS.
PS: I am working in Android.
Thanks to everyone
答案1
得分: 1
你基本上想要同时使用默认的受信任证书和你自己的受信任证书。类似的问题和答案在这里提供了:https://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm
我也遇到了同样的问题,并发现了Code a Ray的答案非常有用。在多个项目中使用了他的代码片段后,我将其制作成了一个库。你可以在这里找到它:sslcontext-kickstart
对于你的用例,以下代码段将使用包含在信任库文件中的证书进行操作:
SSLFactory sslFactory = SSLFactory.builder()
.withDefaultTrustMaterial()
.withTrustMaterial("my-truststore.jks", "password".toCharArray())
.build();
HttpsURLConnection httpsURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpsURLConnection.setHostnameVerifier(sslFactory.getHostnameVerifier());
httpsURLConnection.setSSLSocketFactory(sslFactory.getSslContext().getSocketFactory());
英文:
You basically want to use the default trusted certificates as well as your own trusted certificates. Similar question and answers have been provided here: https://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm
I also ran into the same issue and found the answer of Code a Ray really useful. After using his code snippet for multiple projects I created a library out of it. You can find it here: sslcontext-kickstart
For your use case the following snipper with your certificates wrapped in a truststore file should do the trick:
SSLFactory sslFactory = SSLFactory.builder()
.withDefaultTrustMaterial()
.withTrustMaterial("my-truststore.jks", "password".toCharArray())
.build();
HttpsURLConnection httpsURLConnection = (HttpURLConnection) new URL(url).openConnection();
httpsURLConnection.setHostnameVerifier(sslFactory.getHostnameVerifier());
httpsURLConnection.setSSLSocketFactory(sslFactory.getSslContext().getSocketFactory());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论