How can I set my HttpsURLConnection
to trust a specific certificate only? Currently my code is set to trust all certificates. But the requirement is to trust only a specific certificate and do not trust the others. How can I do it in Java? I'm using JDK 1.5.
Asked
Active
Viewed 5,351 times
4

Arci
- 6,647
- 20
- 70
- 98
-
Is this self-signed certificate valid for the host name in the URL you're trying to contact? – Bruno Jul 27 '12 at 09:24
-
possible duplicate of [How do I accept a self-signed certificate with a Java HttpsURLConnection?](http://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection) – Bruno Jul 27 '12 at 15:20
2 Answers
3
You can trust a specific certificate by creating a custom SSLSocketFactory and providing your own TrustManager. See...
Trusting all certificates using HttpClient over HTTPS
and
How can I use different certificates on specific connections?
In your TrustManager, you will be handed the certificate chain from the client / server to verify against your specific certificate.

Community
- 1
- 1

Todd Trotter
- 61
- 2
-
7The first link ("trusting all certificates [...]") is precisely what shouldn't be done (if you want to prevent MITM attacks). – Bruno Jul 27 '12 at 09:22
-
Bruno is correct. You should absolutely provide a mechanism for verifying the server / client certificate. – Todd Trotter Jul 27 '12 at 15:18
-
Thanks! :) Was able to do it using the 2nd link. Yup, if you're trusting all certificates when using https, then https is useless. – Arci Aug 22 '12 at 08:33