Reputation: 12420
I have a simple server program collecting data from numerous hardware devices on an open wireless network. I want to make sure that whoever connects to my port can't send commands or listen to my traffic so I need the server to validate the client. I have found a few examples but most seem to take the approach of validating the server from the client side. I'm new to SSL and Socket programming.
From the client I have
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("KeyStore"), "password".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = tmf.getTrustManagers();
context.init(null, trustManagers, null);
SSLSocketFactory sf = context.getSocketFactory();
return (SSLSocket) sf.createSocket(host, port);
And on the server I have
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(newFileInputStream("server"),"password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "password".toCharArray());
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
server = (SSLServerSocket) ssf.createServerSocket(this.port);
I'm not exactly sure what everything is doing, but from the example I found it's 2-way authentication, so some overkill. I think I need just one of these pieces of code but don't understand SSL well enough to know which. Which side needs the keystore? Who needs keys and certs? Thanks
Upvotes: 3
Views: 7964
Reputation: 8938
If you just want to add client authentication to your existing server authentication, add this line at the end of your server code:
server.setNeedClientAuth(true);
If you only want the server to authorize the client and not vice versa, call server.setUseClientMode(true)
in the server, and setUseClientMode(false)
on the SSLSocket you create on the client before returning it. Note that this option means that the client devices might be connecting to someone else's server, and would have no way of knowing about it.
In either case, the server will need a trust store - which can be the same as its keystore - with a copy of the certificate(s) the clients are presenting installed. The clients will need key pairs that present this certificate(s).
Upvotes: 3