How to make TLS work with java?

I developed an application that works with TCP sockets.

Now I would like it to work with a TLS connection.

I searched for some resources for 2 days, but there is nothing like a tutorial on how to implement TLS.

Here is what I understood with what I need to do:

  • I need to import a root certificate authority into my keystore.
  • I need to import several other certificates into the / truststore key store.

I cannot find a clear code sample that really explains what to do.

Could you help me with some client / server examples or another useful tutorial? (I already tried looking for "TLS java", "TLS Java example", "TLS Java tutorial" .... But I could not find anything nice.)

Thank you in advance for your attention.

+6
source share
1 answer

There are two ways to achieve this.

The easiest Java protocol support and URL object.

But since I think you already understood that the new URL("https://www.google.com").openStream() gives you a clear text input stream, dealing with all the TLS / SSL materials for you, I will go on the "hard" way :)

Just before answering another question: import CA. CA certificates are located in your java house in any of the following locations: $JAVA_HOME/lib/security/cacerts (JRE) or $JAVA_HOME/jre/lib/security/cacerts (JDK; pay attention to "jre" immediately after the java house) for the default password is "changeit"

To list its contents, you can use the keytool command:

 $ keytool -list -keystore cacerts -storepass changeit 

To add a new certificate, simply use the -import subcommand instead of -list

So, now release the "hard" method (client code):

 import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; ... String host = "www.google.com"; int port = 443; SocketFactory basicSocketFactory = SocketFactory.getDefault(); Socket s = basicSocketFactory.createSocket(host,port); // s is a TCP socket SSLSocketFactory tlsSocketFactory = SSLSocketFactory.getDefault(); s = tlsSocketFactory.createSocket(s, host, port, true); // s is now a TLS socket over TCP 

it is so simple.

If you need a server socket, the code is almost the same, you just need to exchange SocketFactory for ServerSocketFactory and SSLSocketFactory for SSLServerSocketFactory

hope this helps

+13
source

Source: https://habr.com/ru/post/972593/


All Articles