Reputation: 147
I am setting up a licensing servlet in Java together with a client app that will post request for new licenses and validate existing licenses at that server. The servlet runs in Tomcat. I've configured Tomcat so that it only allows connections to the servlet over https, and this works just fine.
I have created a self-signed certificate using 'keytool -genkey -alias www.mysite.com -keyalg RSA -keystore license.store'
which creates a file license.store
and pointed tomcat to this keystoreFile with its password asdf1234
.
When I just try to connect from the client to the servlet over https in Java, I receive the familiar PKIX path building failed
because the certificate is not in the truststore. I tried to fixed this using this suggestion resulting in the code below:
private SSLSocketFactory getSSLFactory() throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = this.getClass().getResourceAsStream("license.store");
if(is ==null) {
return null;
}
keyStore.load(is, "asdf1234".toCharArray());
is.close();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
return ctx.getSocketFactory();
}
After which I call:
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setSSLSocketFactory(getSSLFactory());
which results in a succesfull connection.
Now the problem is that I only get this to work when I copy the license.store
to the client and load that into the KeyStore.load()
. It doesn't strike me as very safe to copy the private key and its password that the server uses to the client. Is there any way to extract only the public key from the license.store and use that? I've been searching this forum and others for a day now and just can't seem to get it.
Upvotes: 0
Views: 3629
Reputation: 42030
You shouldn't be generating a public-private key pair, but rather import the certificate of the server into your (the client's) Java truststore. The certificate is not a secret, and thus does not provide a security risk on the client side. See the -import
option for keytool. Here's in an example.
Upvotes: 3