I’m working in Java with Apache’s HTTPClient and trying to connect to graph.facebook.com. I’m getting “SSLPeerUnverifiedException: No peer certificate” errors, so I guess Facebook’s CA isn’t in the default keystore. So I need to create my own keystore with all the certificates that I want to trust, yes? So I found the following command for obtaining the certificate:
echo | openssl s_client -connect graph.facebook.com:443 2>&1 | \
sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem
Don’t know what’s going on there, but it seems to have worked. I added the cert to a Bouncy Castle formatted keystore. I created an SSLSocketFactory using the new keystore, but it still doesn’t work.
My first guess was, perhaps I don’t have all the certificates in the chain (apparently these things come in chains). So how do I know whether there are so-called “intermediate” CAs involved? And how do I grab those certificates? Am I even on the right track?
I finally had time to look into this, and it turns out it’s super easy! I was only missing ONE option to the openssl command: the showcerts option. Below is an example for obtaining certificates suitable for connecting to Facebook’s image server.
Note: I also found out that to authenticate an SSL connection you do NOT want to add the certificate of the endpoint you are connecting to in your keystore. You only want the intermediate and root Certificate Authorities. In some cases, only the root CA or else you will get an exception. See this great blog post for more info.