Implementing TLS with a NIO client/server

I have been scratching my head trying to come up with a TLS implementation across a client and server setup.

Notes and snippets I have written down about some of the basic setup:

SSLContext context = SSLContext.getInstance("TLS");

// key managers, trust managers

context.init(keyManagers, trustManagers, null);

// Server
SSLEngine engine = context.createSSLEngine();
engine.setClientMode(false);
engine.setNeedClientAuth(true);
// Client
SSLEngine engine = context.createSSLEngine("ip", port);
engine.setClientMode(true);

// Send and receive with networkBuffer

// Reading from
ByteBuffer actualBuffer = ...;
engine.unwrap(networkBuffer, actualBuffer);

// Writing to
ByteBuffer unsecureBuffer = ...;
engine.wrap(unsecureBuffer, networkBuffer);

// Closing
engine.closeInbound();
engine.closeOutbound();

What I believe I have to do to handle this:
Create a set of keys on the client, and then send the public key to the server, and somehow the server will be able to read and write the necessary data.

I understand that there are major gaps in my understanding of how to send the keys from the client to the server, and I would appreciate if someone with a little more experience about using the SSL classes in the standard Java packages could shed some light on how this is handled.

The SSL/TLS handshake is a semi-manual process in NIO. You will be notified of the state of the handshake, and make the appropriate callsbacks to the SSLEngine. Just read the javadocs.

If you prefer handholding, go from here:
https://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/samples/sslengine/SSLEngineSimpleDemo.java

N.B.:
You really don’t want to go this route. What made you think you needed NIO TLS?

I’m trying out all of the different ways to do networking in Java. I started with datagram sockets, then TCP sockets, then NIO UDP, then NIO TCP, and then NIO TCP encrypted, and now NIO TLS. :slight_smile:

Edit: I’ve decided to try out a different method of encrypting data simply with assymetric keys so I guess I don’t necessarily need an answer ATM.