Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HttpsURLConnection and TLS 1.2

I read in an article that HttpsURLConnection will transparently negotiate the SSL connection.

The official document says:

This class uses HostnameVerifier and SSLSocketFactory. There are default implementations defined for both classes. [1]

Does that mean once you open a connection with

httpsCon = (HttpsURLConnection) url.openConnection(); 

It is already SSL/TLS encrypted without any more hassle?

How can I view and set the TLS version for the standard implementation? (Should be TLS 1.2 for Java 8 and TLS 1.0 for Java 7)

References

  1. Oracle Corp. (2011). javax.net.ssl.HttpsURLConnection. (JavaDoc)
like image 867
Marc Wittmann Avatar asked May 08 '15 10:05

Marc Wittmann


People also ask

How do I enable TLS 1.2 in Java?

If your application runs on Java 1.7 or Java 1.6 (update 111 or later), you can set the https. protocols system property when starting the JVM to enable additional protocols for connections made using the HttpsURLConnection class – for example, by setting -Dhttps. protocols=TLSv1. 2 .

What version of TLS does Java 11 use?

The JDK 11 release includes an implementation of the Transport Layer Security (TLS) 1.3 specification (RFC 8446). For more details including a list of the features that are supported, refer to the Java Secure Socket Extension (JSSE) Reference Guide documentation and JEP 332.


2 Answers

You will have to create an SSLContext to set the Protocoll:

in Java 1.8:

 SSLContext sc = SSLContext.getInstance("TLSv1.2");  // Init the SSLContext with a TrustManager[] and SecureRandom()  sc.init(null, trustCerts, new java.security.SecureRandom());  

in Java 1.7:

 SSLContext sc = SSLContext.getInstance("TLSv1");  // Init the SSLContext with a TrustManager[] and SecureRandom()  sc.init(null, trustCerts, new java.security.SecureRandom()); 

then you just have to set the SSLContext to the HttpsURLConnection:

httpsCon.setSSLSocketFactory(sc.getSocketFactory()); 

That should do the Trick.

like image 108
JoCoaker Avatar answered Sep 21 '22 21:09

JoCoaker


You can also set TLS 1.2 protocol with the JDK 1.7. By default JDK 1.7 will set it to 1.0.

SSLContext sc = SSLContext.getInstance("TLSv1.2"); //$NON-NLS-1$ sc.init(null, null, new java.security.SecureRandom()); HttpsURLConnection con = (HttpsURLConnection) httpsURL.openConnection(); con.setSSLSocketFactory(sc.getSocketFactory()); 
like image 34
Kondal Kolipaka Avatar answered Sep 18 '22 21:09

Kondal Kolipaka