Java HttpsURLConnection and TLS 1.2
我读过一篇文章,其中
官方文件说:
This class uses HostnameVerifier and SSLSocketFactory. There are default implementations defined for both classes. [1]
这是否意味着一旦您与
1 | httpsCon = (HttpsURLConnection) url.openConnection(); |
它已经被SSL / TLS加密了,没有更多麻烦了吗?
如何查看和设置标准实施的TLS版本?
(对于Java 8应该是TLS 1.2,对于Java 7应该是TLS 1.0)
参考文献
您将必须创建一个
在Java 1.8中:
1 2 3 | SSLContext sc = SSLContext.getInstance("TLSv1.2"); // Init the SSLContext with a TrustManager[] and SecureRandom() sc.init(null, trustCerts, new java.security.SecureRandom()); |
在Java 1.7中:
1 2 3 | SSLContext sc = SSLContext.getInstance("TLSv1"); // Init the SSLContext with a TrustManager[] and SecureRandom() sc.init(null, trustCerts, new java.security.SecureRandom()); |
那么您只需将SSLContext设置为HttpsURLConnection:
1 | httpsCon.setSSLSocketFactory(sc.getSocketFactory()); |
这应该够了吧。
您还可以使用JDK 1.7设置TLS 1.2协议。 默认情况下,JDK 1.7会将其设置为1.0。
1 2 3 4 | 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()); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); |
上面的代码可用于在Java 1.7中启用tls 1.1或tls 1.2