Reputation: 11724
I am trying to connect to a SSL web server. We currently have a pkcs12 file and connect, that is our private-key and certificate. Is it possible to connect using Java code with a public-key and certificate. Imagine I have a file (it is digital but here is the pem output).
> Myfile.pk12 / Myfile.pem
>
> -----BEGIN CERTIFICATE----- ...
> -----END CERTIFICATE-----
>
> -----BEGIN ENCRYPTED PRIVATE KEY----- ...
> -----END ENCRYPTED PRIVATE KEY-----
And we can connect to the server with this:
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
KeyStore keyStore = generateKeyStore();
System.out.println("==>" + keyStore);
SSLSocketFactory socketFactory = new SSLSocketFactory(
SSLSocketFactory.TLS,
keyStore,
KEYSTORE_PASSCODE,
null,
null,
(X509HostnameVerifier) SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
...
This works, but let's say we connect with the certificate and public key. Wouldn't Java internally create a private key based on the keystore we provide and that would allow us to connect? E.g.
> MyfileNEW.pk12 / MyfileNEW.pem
>
> -----BEGIN CERTIFICATE----- ...
> -----END CERTIFICATE-----
>
> -----BEGIN PUBLIC KEY----- ...
> -----END PUBLIC KEY-----
If the public key is embedded in the certificate? Can I use Java to send a request to the server without pre-creating a private key?
Upvotes: 0
Views: 1932
Reputation: 12958
If the server requires a 2-way (mutual) SSL connection (where the client must be authenticated by the server and the server must be trusted by the client), then you need to provide 2 keystores. One containing the private key and public certificate, and the other containing a list of trusted certificate authorities (CAs).
If the server allows 1-way SSL (where the client must trust the server), then you only need to provide one keystore containing a list of trusted CAs.
You can't create a private key from the public key. That would defeat the purpose.
Check out the documentation of SSLSocketFactory for more details.
But notice that this class is deprecated. It recommends that you use SSLConnectionSocketFactory instead.
Upvotes: 1