1. ホーム
  2. java

java.security.InvalidAlgorithmParameterException: TrustAnchors パラメータは空であってはなりません 解決策

2022-02-17 02:42:35

エラー報告には

javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at org.apache.axis.AxisFault.makeFault(AxisFault.java:101)

下記の記事を参考に解決しました。ツール

/*
 * Log changed by Date Desc
 * L48972_1 huang.hui 2018-12-18 Calling the interface, bypassing authentication
*/
package com.css.eshop.util;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.certificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;
import javax.net.ssl;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket;
import org.apache.http.conn.socket;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.css.eshop.model.Respones;
import com.css.eshop.model.TokenVo;
import com.google.gson.Gson;

public class HttpClientNoValidation {
	protected static Log logger = LogFactory.getLog(HttpClientUtil.class);
	/**
	 * Bypass validation
	 * 	
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 */
	public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext sc = SSLContext.getInstance("SSLv3");
 
		// implement an X509TrustManager interface for bypassing authentication without modifying the methods inside
		X509TrustManager trustManager = new X509TrustManager() {
			@Override
			public void checkClientTrusted(
					java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}
 
			@Override
			public void checkServerTrusted(
					java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}
 
			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
 
		sc.init(null, new TrustManager[] { trustManager }, null);
		return sc;
	}
	/**
	 * Simulate a request
	 * 
	 * @param url resource address
	 * @param map List of parameters
	 * @param encoding encoding
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static String sendPost(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
		String body = "";
		// Use authentication bypass to handle https requests
		SSLContext sslcontext = createIgn
		String strResult = "";
		Respones responseVo = new Respones();
		// use authentication bypass to handle https requests
		SSLContext sslcontext = createIgnoreVerifySSL();
		
        // set the protocol http and https corresponding to the object that handles the socket link factory
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);
 
        // Create a custom httpclient object
		CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response=null;
		try {
		// Create a post request object
		//HttpPost httpPost = new HttpPost(url);
		HttpGet httpget= new HttpGet(url);
		//Load parameters
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if(map!=null){
			for (Entry<String, String> entry : map.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		//set the parameters to the request object
		//httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
 
		System.out.println("Request address: "+url);
		System.out.println("Request parameters: "+nvps.toString());
		
		//set header information
		//specify the message header [Content-type], [User-Agent]
		httpget.setHeader("Content-type", "application/x-www-form-urlencoded");
		httpget.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		
		//execute the request operation and get the result (synchronous blocking)
		 response = client.execute(httpget);
		//get the result entity
		HttpEntity entity = response.getEntity();
		int iGetResultCode = response.getStatusLine().getStatusCode();
		if (entity ! = null) {
			//Convert the result entity to String by the specified encoding
			//body = EntityUtils.toString(entity, encoding);
			strResult = EntityUtils.toString(entity);
		}
	
		responseVo.setResponeCde(iGetResultCode);
		responseVo.setResult(strResult);
		//EntityUtils.consume(entity);
		} catch (Exception ex) {
			responseVo.setResponeCde(500);
			responseVo.setResult("error");
			logger.error("executeGetMethod", ex);
		} finally {
			 try {
				if(response ! =null){
					response.close();
				}
			} catch (Exception e) {
				logger.error("executeGetMethod", e);
			}
		}
		//release the link
		response.close();
        return responseVo;
	}
	/**
	 * Simulate the request Get()
	 * 
	 * @param url Resource address
	 * @param map list of parameters
	 * @param map token
	 * @param encoding encoding
	 * @return
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static Respones sendTokenToGet(String url, Map<String,String> map,Respones tokenRespones,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
		//handle the token parameter start
		String token = tokenRespones.getResult();
         if(tokenRespones.getResponeCde() >= 303){
         	return tokenRespones;
         }
         Gson gson = new Gson();
         TokenVo t = gson.fromJson(token, TokenVo.class);
         logger.info(" Token\t: " + t.getToken());
         token = t.getToken();
       //handle the token parameter end
         
		String body = "";
		String strResult = "";
		Respones responseVo = new Respones();
		// use authentication bypass to handle https requests
		SSLContext sslcontext = createIgnoreVerifySSL();
		
     

エンティティクラスです。


import java.io;

public class Respones implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	private int responeCde;
	
	private String result;

	public int getResponeCde() {
		return responeCde;
	}

	public void setResponeCde(int responeCde) {
		this.responeCde = responeCde;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
}

package com.css.eshop.model;

public class TokenVo {

	private String ip;
	private String token;
	private String expiration;

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getExpiration() {
		return expiration;
	}

	public void setExpiration(String expiration) {
		this.expiration = expiration;
	}
}


    public static void main(String[] args) throws ParseException, IOException, KeyManagementException, NoSuchAlgorithmException, HttpProcessException {
        String url = "https://sso.tgb.com:8443/cas/login";
        String body = send(url, null, "utf-8");
        System.out.println("Transaction response result: ");
        System.out.println(body);
        System.out.println("-----------------------------------");
    }


pythonではrequests.get(url,verify=False)が設定されているのでOKです。

参考記事 HttpClientの設定sslを簡単に弄る、バイパス証明書認証を使ってhttpsを実現する

httpclientは、直接httpsのリソースにアクセスすることはできませんが、今回は、環境をシミュレートし、それをテストするためにhttpsを設定することができます。前回の記事で、tomcatにSSLを自作して設定した記事を共有しましたので、それに従って、ローカルにhttpsを設定することができます。

すでに証明書は信頼されており(薄緑色の小さな鍵が表示されています)、ブラウザは正常にアクセスできることがわかります。では、コードでテストしてみましょう。

/**
     * Bypass authentication
     *     
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");
 
        // implement an X509TrustManager interface for bypassing authentication without modifying the methods inside
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }
 
            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }
 
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
 
        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }
Then modify the original send method to.
    /**
     * Simulate the request
     * 
     * @param url resource address
     * @param map List of parameters
     * @param encoding encoding
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
        String body = "";
        // Use authentication bypass to handle https requests
        SSLContext sslcontext = createIgnoreVerifySSL();
        
        // set the protocol http and https corresponding to the object that handles the socket link factory
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);
 
        // Create a custom httpclient object
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
        
        // create a post request object
        HttpPost httpPost = new HttpPost(url);
        
        //Fill parameters
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        // Set the parameters to the request object
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
 
        System.out.println("Request address: "+url);
        System.out.println("Request parameters: "+nvps.toString());
        
        //set header information
        //specify the message header [Content-type], [User-Agent]
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        
        // Perform the request operation and get the result (synchronous blocking)
        CloseableHttpResponse response = client.execute(httpPost);
        //Get the result entity
        HttpEntity entity = response.getEnt



例外がスローされたので、2つのオプション(私が知らないオプションもあるかもしれません)を知っています。ここでは最初のオプションを紹介します。コードを直接見てみましょう。


/**
     * Bypass authentication
     *     
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");
 
        // implement an X509TrustManager interface for bypassing authentication without modifying the methods inside
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }
 
            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }
 
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
 
        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }
Then modify the original send method to.
    /**
     * Simulate the request
     * 
     * @param url resource address
     * @param map List of parameters
     * @param encoding encoding
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
        String body = "";
        // Use authentication bypass to handle https requests
        SSLContext sslcontext = createIgnoreVerifySSL();
        
        // set the protocol http and https corresponding to the object that handles the socket link factory
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);
 
        // Create a custom httpclient object
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
        
        // create a post request object
        HttpPost httpPost = new HttpPost(url);
        
        //Fill parameters
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        // Set the parameters to the request object
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
 
        System.out.println("Request address: "+url);
        System.out.println("Request parameters: "+nvps.toString());
        
        //set header information
        //specify the message header [Content-type], [User-Agent]
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        
        // Perform the request operation and get the result (synchronous blocking)
        CloseableHttpResponse response = client.execute(httpPost);
        //Get the result entity
        HttpEntity entity = response.getEnt


もう一度テストして、合格することを確認します。
--------------------- 
元記事: https://blog.csdn.net/xiaoxian8023/article/details/49865335 
参考ブログ

https://blog.csdn.net/xiaoxian8023/article/category/5968067