问题
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.
回答1:
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:
- This answer (which also contains a link to a book chapter).
- Notes from Jean-François Arcand who implemented it in Grizzly.
- An example of the type of problems you can get with asynchronous SSL/TLS.
- Getting familiar with the problems mentioned in these this question should also be relevant (in particular, how to deal with them in async mode).
- The Simple Framework also has support for async SSL/TLS.
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.
回答2:
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 SSL with Java NIO may be helpful.
回答3:
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.
来源:https://stackoverflow.com/questions/9118367/java-nio-channels-and-tls