简体   繁体   English

Java HttpsURLConnection和TLS 1.2

[英]Java HttpsURLConnection and TLS 1.2

I read in an article that HttpsURLConnection will transparently negotiate the SSL connection. 我在一篇文章中读到HttpsURLConnection将透明地协商SSL连接。

The official document says: 官方文件说:

This class uses HostnameVerifier and SSLSocketFactory. 该类使用HostnameVerifier和SSLSocketFactory。 There are default implementations defined for both classes. 为这两个类定义了默认实现。 [ 1 ] [ 1 ]

Does that mean once you open a connection with 这是否意味着一旦你打开一个连接

httpsCon = (HttpsURLConnection) url.openConnection();

It is already SSL/TLS encrypted without any more hassle? 它已经加密了SSL / TLS而没有任何麻烦吗?

How can I view and set the TLS version for the standard implementation? 如何查看和设置标准实现的TLS版本? (Should be TLS 1.2 for Java 8 and TLS 1.0 for Java 7) (应该是Java 8的TLS 1.2和Java 7的TLS 1.0)

References 参考

  1. Oracle Corp. (2011). 甲骨文公司(2011年)。 javax.net.ssl.HttpsURLConnection . javax.net.ssl.HttpsURLConnection (JavaDoc) (JavaDoc的)

You will have to create an SSLContext to set the Protocoll: 您必须创建一个SSLContext来设置Protocoll:

in Java 1.8 : 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 : 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 : 那么你只需要将SSLContext设置为HttpsURLConnection

httpsCon.setSSLSocketFactory(sc.getSocketFactory());

That should do the Trick. 这应该够了吧。

You can also set TLS 1.2 protocol with the JDK 1.7. 您还可以使用JDK 1.7设置TLS 1.2协议。 By default JDK 1.7 will set it to 1.0. 默认情况下,JDK 1.7将其设置为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());
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 上面的代码可用于在java 1.7中启用tls 1.1或tls 1.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM