SSL - SSLHandshakeException: No subject alternative names present

襲冷發表於2018-08-08

一、異常日誌

javax.net.ssl.SSLHandshakeException:
    Caused by: java.security.cert.CertificateException: No subject alternative names present
        at sun.security.util.HostnameChecker.matchIP(Unknown Source)
        at sun.security.util.HostnameChecker.match(Unknown Source)
	at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
	at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
	at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
	at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
	... 12 more

二、問題程式碼

public class SslHandshakeExc_NsanPresent{
	
	public static void main(String[] args) throws Exception {

		URL url = new URL("https://192.168.2.222:8443/wbsystem/login.jsp");

		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

		conn.connect();

		InputStream is = conn.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}

		br.close();
		is.close();

	}
    
}

三、解決方案

public class SslHandshakeExc_NsanPresent{
	
	public static void main(String[] args) throws Exception {

		URL url = new URL("https://192.168.2.222:8443/wbsystem/login.jsp");

		// 新增部分
		SSLContext sc = SSLContext.getInstance("TLS");
		sc.init(null, trustAllCerts, null);
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

		// 新增部分
		conn.setHostnameVerifier(new Servlet_test().new TrustAnyHostnameVerifier());

		conn.connect();

		InputStream is = conn.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}

		br.close();
		is.close();

	}

	// 定製Trust
	static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

		@Override
		public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		@Override
		public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		@Override
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}
		
	} };

	// 定製Verifier
	public class TrustAnyHostnameVerifier implements HostnameVerifier {
		
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
		
	}
}

 

 

 

 

 

相關文章