Java.nio Channels and TLS
Asked Answered
N

3

17

How do I secure a Java SocketChannel, ServerSocketChannel or, perhaps even, a DatagramChannel with TLS?

I know that there are some frameworks (#1 #2) that advertise to be able, but I want to know if it is possible to achieve this with the pure Java standard library alone.

Nonfeasance answered 2/2, 2012 at 19:6 Comment(2)
exampledepot.com/egs/javax.net.ssl/client.htmlSightread
@MauricioLinhares: these examples are for SSLSockets, not NIO.Bogusz
B
22

You need to use the SSLEngine, as documented in Non-blocking I/O with SSLEngine. The libraries you mention use it or use libraries that use it.

(Note that this is notoriously difficult to use.)

You may find these links interesting:


For Datagrams, you should look into using DTLS instead of TLS. I'm not sure of its implementation status in Java, but you could dig through the archives of the java.openjdk.security.devel mailing list.

Bogusz answered 2/2, 2012 at 19:18 Comment(0)
U
9

You need to use SSLEngine and do the handshake manually using that state machine. SSL/TLS is implemented on top of TCP so you can not use it directly on top of a DatagramChannel.

The article Non-blocking I/O with SSLEngine may be helpful.

Untruth answered 2/2, 2012 at 19:16 Comment(1)
The link for O'reilly is dead it seemsAbjuration
J
6

As Bruno correctly mentions, the standard way of doing that is using SSLEngine. But that class is seriously hard to use.

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.

Jordans answered 22/7, 2017 at 23:41 Comment(3)
Nice! Any plans to support AsynchronousSocketChannel in that library?Unreflecting
@jyemin, seems doable and should be possible justs as an added layer on top of the existing interface. Somehow we would need to wrap a selector loop like the one we have already as a test. Pull requests welcome! :-)Jordans
@jyemin, hope it's not too late, but the latest release included asynchronoust channel support.Jordans

© 2022 - 2024 — McMap. All rights reserved.