SSL通关之代码示例(四)

实际开发过程中,服务器端是不需要多加代码处理的,因为ssl验证过程是由服务器(tomcat、nginx等)完成的。

这段代码也是参考了网上的:

新建一个web项目,项目结构和需要引入的jar如下:

 

web.xml配置:

 

[html]  view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  
  3.   <display-name>Secure Sockets Layer</display-name>  
  4.   <servlet>  
  5.     <servlet-name>SSLServlet</servlet-name>  
  6.     <servlet-class>com.sengle.cloud.servlet.SSLServlet</servlet-class>  
  7.   </servlet>  
  8.   <servlet-mapping>  
  9.     <servlet-name>SSLServlet</servlet-name>  
  10.     <url-pattern>/sslServlet</url-pattern>  
  11.   </servlet-mapping>  
  12.   <welcome-file-list>  
  13.     <welcome-file>index.jsp</welcome-file>  
  14.   </welcome-file-list>  
  15.     
  16.   <!-- SSL配置 -->  
  17.   <security-constraint>  
  18.     <web-resource-collection>  
  19.       <web-resource-name>SSL</web-resource-name>  
  20.       <url-pattern>/*</url-pattern>  
  21.     </web-resource-collection>  
  22.     <user-data-constraint>  
  23.       <description>SSL required</description>  
  24.       <transport-guarantee>CONFIDENTIAL</transport-guarantee>  
  25.     </user-data-constraint>  
  26.   </security-constraint>  
  27. </web-app>  

 

服务器端,写了个servlet(注意配置到web.xml中),代码如下:

 

[java]  view plain copy
 
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3. import java.security.cert.X509Certificate;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. public class SSLServlet extends HttpServlet {  
  11.   
  12.     private static final long serialVersionUID = 1601507150278487538L;  
  13.     private static final String ATTR_CER = "javax.servlet.request.X509Certificate";  
  14.     private static final String CONTENT_TYPE = "text/plain;charset=UTF-8";  
  15.     private static final String DEFAULT_ENCODING = "UTF-8";  
  16.     private static final String SCHEME_HTTPS = "https";  
  17.   
  18.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  19.             throws ServletException, IOException {  
  20.         response.setContentType(CONTENT_TYPE);  
  21.         response.setCharacterEncoding(DEFAULT_ENCODING);  
  22.         PrintWriter out = response.getWriter();  
  23.         X509Certificate[] certs = (X509Certificate[]) request.getAttribute(ATTR_CER);  
  24.         if (certs != null) {  
  25.             int count = certs.length;  
  26.             out.println("共检测到[" + count + "]个客户端证书");  
  27.             for (int i = 0; i < count; i++) {  
  28.                 out.println("客户端证书 [" + (++i) + "]: ");  
  29.                 out.println("校验结果:" + verifyCertificate(certs[--i]));  
  30.                 out.println("证书详细:\r" + certs[i].toString());  
  31.             }  
  32.         } else {  
  33.             if (SCHEME_HTTPS.equalsIgnoreCase(request.getScheme())) {  
  34.                 out.println("这是一个HTTPS请求,但是没有可用的客户端证书");  
  35.                 request.setAttribute("user""username");  
  36.                 out.println(request.getAttribute("user"));  
  37.             } else {  
  38.                 out.println("这不是一个HTTPS请求,因此无法获得客户端证书列表 ");  
  39.                   
  40.             }  
  41.         }  
  42.         out.close();  
  43.     }  
  44.   
  45.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  46.             throws ServletException, IOException {  
  47.         doGet(request, response);  
  48.     }  
  49.       
  50.     /** 
  51.      * <p> 
  52.      * 校验证书是否过期 
  53.      * </p> 
  54.      *  
  55.      * @param certificate 
  56.      * @return 
  57.      */  
  58.     private boolean verifyCertificate(X509Certificate certificate) {  
  59.         boolean valid = true;  
  60.         try {  
  61.             certificate.checkValidity();  
  62.         } catch (Exception e) {  
  63.             e.printStackTrace();  
  64.             valid = false;  
  65.         }  
  66.         return valid;  
  67.     }  

 

 

客户端代码:

 

[java]  view plain copy
 
  1. /** 
  2.  * Copyright (C) 2011-2014 sgcc Inc.  
  3.  * All right reserved.  
  4.  * modify info: 
  5.  */  
  6. package com.sengle.cloud.client;  
  7.   
  8. import java.io.BufferedReader;  
  9. import java.io.File;  
  10. import java.io.FileInputStream;  
  11. import java.io.InputStream;  
  12. import java.io.InputStreamReader;  
  13. import java.security.KeyStore;  
  14.   
  15. import org.apache.http.HttpEntity;  
  16. import org.apache.http.HttpResponse;  
  17. import org.apache.http.client.HttpClient;  
  18. import org.apache.http.client.methods.HttpGet;  
  19. import org.apache.http.conn.scheme.Scheme;  
  20. import org.apache.http.conn.ssl.SSLSocketFactory;  
  21. import org.apache.http.impl.client.DefaultHttpClient;  
  22. import org.apache.http.util.EntityUtils;  
  23.   
  24.   
  25. public class HttpsClient {  
  26.     private static final String KEY_STORE_TYPE_TRUST = "jks"//如果证书为bks格式,那么要改为bks,同时下面的KEY_STORE_TYPE_CLIENT也要改为bks  
  27. //    private static final String KEY_STORE_TYPE_CLIENT = "PKCS12"; //如果KEY_STORE_TYPE_TRUST为jks,则KEY_STORE_TYPE_CLIENT为PKCS12  
  28.     private static final String KEY_STORE_TYPE_CLIENT = "PKCS12"//如果KEY_STORE_TYPE_TRUST为bks,则此处也应该为bks。  
  29.     private static final String SCHEME_HTTPS = "https";  
  30.     private static final int HTTPS_PORT = 8443//此处为tomcat中的配置,默认为8443  
  31.     private static final String HTTPS_URL = "https://10.100.100.24:8443/SSL/sslServlet";  
  32.       
  33.     private static final String basePath = "D:/SSL/";  
  34.     private static final String KEY_STORE_CLIENT_PATH = basePath + "/client-24.p12"//如果为bks,那么此处应该为bks格式的证书  
  35.     private static final String KEY_STORE_TRUST_PATH = basePath + "/client-24.truststore"//如果为bks,那么此处应该为bks格式的证书  
  36.     private static final String KEY_STORE_PASSWORD = "123456"//密码  
  37.     private static final String KEY_STORE_TRUST_PASSWORD = "123456";  // 密码  
  38.   
  39.     public static void main(String[] args) throws Exception {  
  40.         ssl();  
  41.     }  
  42.       
  43.     private static void ssl() throws Exception {  
  44.         HttpClient httpClient = new DefaultHttpClient();  
  45.         try {  
  46.             KeyStore keyStore  = KeyStore.getInstance(KEY_STORE_TYPE_CLIENT);  
  47.             KeyStore trustStore  = KeyStore.getInstance(KEY_STORE_TYPE_TRUST);  
  48.             InputStream ksIn = new FileInputStream(KEY_STORE_CLIENT_PATH);  
  49.             InputStream tsIn = new FileInputStream(new File(KEY_STORE_TRUST_PATH));  
  50.             try {  
  51.                 keyStore.load(ksIn, KEY_STORE_PASSWORD.toCharArray());  
  52.                 trustStore.load(tsIn, KEY_STORE_TRUST_PASSWORD.toCharArray());  
  53.             } finally {  
  54.                 try { ksIn.close(); } catch (Exception ignore) {}  
  55.                 try { tsIn.close(); } catch (Exception ignore) {}  
  56.             }  
  57.             //双向验证加载keystore和truststore两个证书  
  58.             SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, KEY_STORE_PASSWORD, trustStore);  
  59.            
  60.             /* 
  61.              * 单向验证,只加载truststore 
  62.             SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); 
  63.             */  
  64.               
  65.             Scheme sch = new Scheme(SCHEME_HTTPS, HTTPS_PORT, socketFactory);  
  66.             httpClient.getConnectionManager().getSchemeRegistry().register(sch);  
  67.             HttpGet httpget = new HttpGet(HTTPS_URL);  
  68.             System.out.println("executing request" + httpget.getRequestLine());  
  69.             HttpResponse response = httpClient.execute(httpget);  
  70.             HttpEntity entity = response.getEntity();  
  71.             System.out.println("----------------------------------------");  
  72.             System.out.println(response.getStatusLine());  
  73.             if (entity != null) {  
  74.                 System.out.println("Response content length: " + entity.getContentLength());  
  75.                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));  
  76.                 String text;  
  77.                 while ((text = bufferedReader.readLine()) != null) {  
  78.                     System.out.println(text);  
  79.                 }  
  80.                 bufferedReader.close();  
  81.             }  
  82.             EntityUtils.consume(entity);  
  83.         } finally {  
  84.             httpClient.getConnectionManager().shutdown();  
  85.         }  
  86.     }  
  87. }  

猜你喜欢

转载自javatea.iteye.com/blog/2120310
今日推荐