Reputation: 339
I developed an application working with TCP sockets. Now I would like it to work with a TLS connection.
I searched some resources for now 2 days but there is nothing that looks like a tutorial on how to implement TLS.
Here is what I understood with what I have to do :
I can't find a clear sample of code that explain really what to do.
Can you please help me with some client/server example or other helpful tutorial? (I already tried to search "TLS java", "TLS Java example", "TLS Java tutorial" etc. But I could not find anything satisfying.)
Thank you in advance for your attention.
Upvotes: 14
Views: 32077
Reputation: 2939
There is two way to achieve this.
The easiest lies in Java protocol support and the URL
object.
But since I think you already figured out that new URL("https://www.google.com").openStream()
gives you a clear text input stream while dealing with all the TLS/SSL stuff for you, I'll go for the "hard" way :)
Just before I'll answer your other question: importing a CA. CA certificates are located in your Java home at either of theses locations:
$JAVA_HOME/lib/security/cacerts
(JRE)$JAVA_HOME/jre/lib/security/cacerts
(JDK; notice the 'jre' just
after the Java home)For both the default password is "changeit".
To list its content you can use the keytool
command:
$ keytool -list -keystore cacerts -storepass changeit
To add a new cert just use the -import
subcommand instead of -list
.
So now let's go for the "hard" way (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's as simple as that.
If you need a server socket the code is almost the same, you just have to exchange SocketFactory
for ServerSocketFactory
and SSLSocketFactory
for SSLServerSocketFactory
.
Hope this helps.
Upvotes: 23