Generate self-signed certificate, private key goes to server, certificate with public key goes to client. After that you need properly set up SSLContext on client side. This can be achieve basically in 3 way.
1 - add server certificate CA (for self-signed CA == certificate) into client $JRE/lib/security/cacerts
file. That not very good, because after JRE update on client you can lost this changes.
2 - put server certificate into keystore and set up environment variables (with System.setProperty
or as -D
command line option) javax.net.ssl.trustStore
, javax.net.ssl.trustStorePassword
and, optionally, javax.net.ssl.trustStoreType
, check this answer for details https://stackoverflow.com/a/5871352/1516873
3 - Manual set up SSLContext trustStoreManager, for example:
private final SSLContext createSSLContext()
throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream("path to server certificate.pem"); // server certificate in PEM format
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(null);
try {
X509Certificate cacert = (X509Certificate) cf.generateCertificate(in);
trustStore.setCertificateEntry("server_alias", cacert);
} finally {
IOUtils.closeQuietly(in);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("SSL"); // TLS e.g.
sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
return sslContext;
}