Java HttpsURLConnection and TLS 1.2

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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)

回答1:

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.



回答2:

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()); 


回答3:

private static javax.net.ssl.SSLSocketFactory getFactorySimple()          throws Exception {     SSLContext context = SSLContext.getInstance("TLSv1.2");`      context.init(null, null, null);      return context.getSocketFactory();  }  String loginurl ="some url"; HttpsURLConnection connection = null; URL url = new URL(loginURL);  connection = (HttpsURLConnection) url.openConnection();  javax.net.ssl.SSLSocketFactory sslSocketFactory =getFactorySimple();  connection.setSSLSocketFactory(sslSocketFactory); 

The above code can be used to enable tls 1.1 or tls 1.2 in java 1.7



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!