SSL communication with sockets
In order for a socket to communicate with the secure SSL protocol, you need to create slightly different objects.
On the server:
ServerSocket serverSocket = new ServerSocket(PORT);
They become:
SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(PORT);
Optionally, if we want to authenticate the client (we will see this later):
serverSocket.setNeedClientAuth(true);
To the client:
Socket clientSocket = new Socket(HOST, PORT);
They become:
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket clientSocket = (SSLSocket) factory.createSocket(HOST, PORT);
Also, you need to set up your private and public keys correctly. And this depends on whether or not we want to authorize the clients public key on the server.
We have two types of necessary warehouses:
- Keystores serve to identify us
- Truststores are used to authorize other parties
Configuration is done through system properties in Java, with this statement:
System.setProperty("nameOfTheProperty", "value");
No client authorization
You need to generate two warehouses:
- serverKeystore.jks - server public/private key
- clientTruststore.jks - server public key
keytool -genkey -alias srvAlias -keyalg RSA -keystore serverKeystore.jks -keysize 2048
keytool -export -keystore serverKeystore.jks -alias srvAlias -file server.crt
keytool -importcert -file server.crt -keystore clientTruststore.jks -alias srvAlias
Configuration on the server to identify yourself:
javax.net.ssl.keyStore=serverKeystore.jks
javax.net.ssl.keyStorePassword=yourpassword
Configuration on the client to accept on the server (only if the server is not authorized by a CA Authority):
javax.net.ssl.trustStore=clientTruststore.jks
javax.net.ssl.trustStorePassword=yourpassword
With client authorization
To the above configurations, you need to add:
- clientKeystore.jks: client public/private key
- serverTruststore.jks: Client public key
keytool -genkey -keyalg RSA -alias cltAlias -keystore clientKeystore.jks -keysize 2048
keytool -export -keystore clientKeystore.jks -alias cltAlias -file client.crt
keytool -importcert -file client.crt -keystore serverTruststore.jks -alias cltAlias
Configuration on the server to accept the client:
javax.net.ssl.trustStore=serverTruststore.jks
javax.net.ssl.trustStorePassword=yourpassword
Configuration on the client to identify itself:
javax.net.ssl.keyStore=clientKeystore.jks
javax.net.ssl.keyStorePassword=yourpassword