Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NIO2 AsynchronousSocketChannel/AsynchronousServerSocketChannel and TLS/SSL

All the sources/samples on the INTERNET that available on NIO2 are without TLS/SSL support,

java.nio.channels.AsynchronousSocketChannel java.nio.channels.AsynchronousServerSocketChannel

As I understand the SSLEngine life-cycle of connection differ from AsynchronousSocketChannel.connect && AsynchronousServerSocketChanne.accept, TLS/SSL should be encapsulated inside the AIO implementation, so how can I use them both...? NOTE: I so in the Grizzly project a video that talk about they already implement it, I look on the source code, but I saw AIO but not TLS/SSL integration...

Thanks in advance!

like image 576
user1740371 Avatar asked Oct 12 '12 07:10

user1740371


2 Answers

The comment on the original question is indeed correct. SSLEngine operates using ByteBuffer directly.

This means it is compatible with AIO. You start by accepting a connection. The client then connects and performs the initial write. To determine if you have enough data buffered use the handshake status and status. The engine will keep telling you "NEED_UNWRAP" if more data needs to be supplied from the other end. So you need to keep a queue of ByteBuffer objects. Same thing, the engine will keep telling you "NEED_WRAP" if more data needs to sent to the other end before it can continue. You keep going until you get "Finished" from the handshake status.

I would recommend however you use something like Netty which makes this much simpler. It should be noted that Netty did have support for AIO in the alpha stages of 4. However, it was shown that AIO was slower than NIO. Hence, it was removed.

However, not only will Netty make things simpler than trying to use NIO or AIO directly but will also make it easy to switch between the two if ever AIO is re-introduced.

A full example of using SSL with Netty can be found here.

like image 185
pjulien Avatar answered Oct 09 '22 04:10

pjulien


The standard way of doing TLS in Java is using SSLEngine. But that class is seriously hard to use. There are some tutorials around, but for a typical application, using SSLEngine should be out of the question. ByteChannel and their friends are not supported directly, and imply a lot of work.

I came across the same problem some time ago and ended up writing my own library. There are some examples out there and of course there is also the code inside projects like Netty, etc. But neither option is robust or easily reusable.

TLS Channel wraps an SSLEngine in a ByteBuffer and allows to use it just like normal SocketChannels. AsynchronousByteChannels are a higher level abstraction that hides the selector loop; the library also supports that.

like image 37
Mariano Barrios Avatar answered Oct 09 '22 04:10

Mariano Barrios