Installing the certificate used by Java SSL ServerSocket

I want to open a secure listening socket in a Java server application. I know that the recommended way to do this is to simply do this:

SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); ServerSocket ss = ssf.createServerSocket(443); 

But for this, you need to transfer the JVM server certificate when java starts. Since this would make some things in the deployment more difficult for me, I would prefer to download the certificate at runtime.

So, I have a key file and password, and I want a server socket. How to get there? Well, I read the documentation, and the only way to find this is:

 // these are my parameters for SSL encryption char[] keyPassword = "P@ssw0rd!".toCharArray(); FileInputStream keyFile = new FileInputStream("ssl.key"); // init keystore KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(keyFile, keyPassword); // init KeyManagerFactory KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyPassword); // init KeyManager KeyManager keyManagers[] = keyManagerFactory.getKeyManagers(); // init the SSL context SSLContext sslContext = SSLContext.getDefault(); sslContext.init(keyManagers, null, new SecureRandom()); // get the socket factory SSLServerSocketFactory socketFactory = sslContext.getServerSocketFactory(); // and finally, get the socket ServerSocket serverSocket = socketFactory.createServerSocket(443); 

And it does not even have error handling. Is it really that hard? Is there an easier way to do this?

+8
java ssl
source share
2 answers

But for this, you need to transfer the JVM server certificate when java starts.

No no. Just set these system properties before creating an SSLServerSocket:

 javax.net.ssl.keyStore ssl.key javax.net.ssl.keyStorePassword P@ssw0rd! 

You can do this using System.setProperties() or on the command line.

+9
source share

If you look at the code, you can understand why this is necessarily complicated. This code separates the SSL protocol implementation from:

  • source of your key material ( KeyStore )
  • Choosing a Certificate Algorithm and Key Management ( KeyManager )
  • trust management rules ( TrustManager ) - not used here
  • secure random algorithm ( SecureRandom )
  • NIO or socket implementation ( SSLServerSocketFactory ) - can use SSLEngine for NIO

Think about what your own implementation will look like if you are trying to achieve the same goals!

+2
source share

All Articles