I developed an application working with TCP sockets.
Now I would like it to work with a TLS connection.
I searched some ressources for now 2 days but there is no
There is two way to achieve this.
The easyest 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) or $JAVA_HOME/jre/lib/security/cacerts
(JDK ; notice the 'jre' just after the java home)
for both the default password is "changeit"
To list it's content you can use 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