zoukankan      html  css  js  c++  java
  • Tomcat双向证书验证

    客户端代码:

    package com.nmore.unclePhone.utils.pay.yiji;
    
    import java.io.FileInputStream;
    import java.security.KeyStore;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.KeyManager;
    import javax.net.ssl.KeyManagerFactory;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.TrustManagerFactory;
    import javax.net.ssl.X509TrustManager;
    
    import org.apache.http.conn.ClientConnectionManager;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    
    //用于进行Https请求的HttpClient
    public class SSLClient extends DefaultHttpClient{
        
        private X509TrustManager sunJSSEX509TrustManagerTomcat;
        private KeyManager[] keyManagers;
        
        private void initTomcat() throws Exception{
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream("C:\Program Files\Java\jdk1.8.0_73\bin\tomcat.keystore"), "123456".toCharArray());
            //ks.load(new FileInputStream("F:\test.keystore"), "123456".toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509",
                    "SunJSSE");
            tmf.init(ks);
            TrustManager tms[] = tmf.getTrustManagers();
            /*
             * Iterate over the returned trustmanagers, look for an instance of
             * X509TrustManager. If found, use that as our "default" trust manager.
             */
            for (int i = 0; i < tms.length; i++) {
                if (tms[i] instanceof X509TrustManager) {
                    sunJSSEX509TrustManagerTomcat = (X509TrustManager) tms[i];
                    return;
                }
            }
            /*
             * Find some other way to initialize, or else we have to fail the
             * constructor.
             */
            throw new Exception("Couldn't initialize");
        }
        private void initClient() throws Exception{
            // First, get the default KeyManagerFactory.
              String alg=KeyManagerFactory.getDefaultAlgorithm();
              KeyManagerFactory kmFact=KeyManagerFactory.getInstance(alg);
                
              // Next, set up the KeyStore to use. We need to load the file into
              // a KeyStore instance.
              FileInputStream fis=new FileInputStream("C:\Program Files\Java\jdk1.8.0_73\bin\client.keystore");
              KeyStore ks=KeyStore.getInstance("jks");
              ks.load(fis, "123456".toCharArray());
              fis.close();
              // Now we initialize the TrustManagerFactory with this KeyStore
              kmFact.init(ks, "123456".toCharArray());
              // And now get the TrustManagers
              keyManagers=kmFact.getKeyManagers();
        }
        
        public SSLClient() throws Exception{
            super();
            if (sunJSSEX509TrustManagerTomcat == null)
                initTomcat();
            if (keyManagers == null)
                initClient();
            
    
            SSLContext ctx = SSLContext.getInstance("TLS");
    
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                    //sunJSSEX509TrustManagerClient.checkClientTrusted(chain, authType);
                }
    
                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                    
                    sunJSSEX509TrustManagerTomcat.checkServerTrusted(chain, authType);
                    
                }
    
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    /*ArrayList<X509Certificate> ars=new ArrayList<X509Certificate>();
                    ars.addAll(Arrays.asList(sunJSSEX509TrustManagerTomcat.getAcceptedIssuers()));
                    ars.addAll(Arrays.asList(sunJSSEX509TrustManagerClient.getAcceptedIssuers()));
                    return ars.toArray(new X509Certificate[ars.size()]);*/
                    return sunJSSEX509TrustManagerTomcat.getAcceptedIssuers();
                }
            };
            
            
        
    
            
            
            ctx.init(keyManagers, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx,
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = this.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        }
    }

    tomcat配置:

      <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" SSLEnabled="true"
                   maxThreads="150" scheme="https" secure="true"
                   clientAuth="true" sslProtocol="TLS"  
                   keystoreFile="C:/Program Files/Java/jdk1.8.0_73/bin/tomcat.keystore" keystorePass="123456"
                   truststoreFile="C:/Program Files/Java/jdk1.8.0_73/bin/client.keystore" truststorePass="123456" 
                   />

    测试代码:

        SSLClient sslClient=new SSLClient();
            HttpPost post = new HttpPost("https://localhost:8443/front/index.xhtml");
    
            
            
            
            post.setEntity(new StringEntity("", ContentType.create(
                    "application/x-www-form-urlencoded","utf-8")));
            HttpResponse response = sslClient.execute(post);
    
            HttpEntity entity = response.getEntity();
            String body = EntityUtils.toString(entity,"utf-8");
    
            System.out.println(body);
  • 相关阅读:
    Oracle和SQLServer中实现跨库查询
    sqlserver中创建链接服务器
    无法从命令行或调试器启动服务,必须首先安装Windows服务(使用installutil.exe),然后用ServerExplorer、Windows服务器管理工具或NET START命令启动它
    Win8系统运行程序提示“占位程序接收到错误数据”的解决方法
    设计模式——简单工厂模式
    设计模式——单例模式
    设计模式——观察者模式
    三一集团提前批java面经
    form表单传到后端的数据乱码
    Failed to obtain the JDBC Connection + Access denied for user 'XXX'@'localhost' (using password: YES)
  • 原文地址:https://www.cnblogs.com/jlx1/p/5226858.html
Copyright © 2011-2022 走看看