解决 JDK1.7 不支持 VCenter 6.7 的问题
问题描述
原项目工程是使用JDK 1.7,可以连接 5.X版本和 6.0版本的 VCenter资源池。
但是,现在VCenter已经升到 6.7版本,原程序对于高版本的 VCenter 6.7 不再试用。
连接 VCenter 6.7 版本的资源池的时候,一直报 SSLHandshakeException 的异常错误。
报错信息如下:
问题处理
1、背景介绍
JDK1.7 默认是 TSLv1, 但是可以支持 TSLv1.1,TSLv1.2;
JDK1.8 默认是 TSLv1.2
2、解决方案
1)如果是脚本访问,可以在连接参数里增加 -Dhttps.protocols=TLSv1.2
2)如果是Java程序处理,想使用 JDK 1.7 访问 VCenter 6.7 资源池,需要对VCenter 6.7版本单独处理
a)根据资源池类型,设置不同的 https.protocols
if (type.equals("VC67")){ java.lang.System.setProperty("https.protocols", "TLSv1.2"); }else{ java.lang.System.setProperty("https.protocols", "TLSv1"); }
b)对于连接VC的认证处理如下:
if (type.equals("VC67")){ trustAllHttpsCertificatesTLS12(); }else { trustAllHttpsCertificates(); }
trustAllHttpsCertificates() 方法如下
private static void trustAllHttpsCertificates() throws Exception { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext(); sslsc.setSessionTimeout(20);// add time out 20 t for session sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); }
trustAllHttpsCertificatesTLS12() 方法如下
private static void trustAllHttpsCertificatesTLS12() throws Exception { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("TLSv1.2"); javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext(); sslsc.setSessionTimeout(20);// add time out 20 t for session sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); }
TrustAllTrustManager 类如下
private static class TrustAllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } }