SSL通关之代码演示样例(四)

实际开发过程中,server端是不须要多加代码处理的,由于ssl验证过程是由server(tomcat、nginx等)完毕的。

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

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

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>Secure Sockets Layer</display-name>
  <servlet>
    <servlet-name>SSLServlet</servlet-name>
    <servlet-class>com.sengle.cloud.servlet.SSLServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>SSLServlet</servlet-name>
    <url-pattern>/sslServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- SSL配置 -->
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>SSL</web-resource-name>
      <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
      <description>SSL required</description>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
  </security-constraint>
</web-app>

server端,写了个servlet(注意配置到web.xml中)。代码例如以下:

import java.io.IOException;
import java.io.PrintWriter;
import java.security.cert.X509Certificate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SSLServlet extends HttpServlet {

    private static final long serialVersionUID = 1601507150278487538L;
    private static final String ATTR_CER = "javax.servlet.request.X509Certificate";
    private static final String CONTENT_TYPE = "text/plain;charset=UTF-8";
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final String SCHEME_HTTPS = "https";

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding(DEFAULT_ENCODING);
        PrintWriter out = response.getWriter();
        X509Certificate[] certs = (X509Certificate[]) request.getAttribute(ATTR_CER);
        if (certs != null) {
            int count = certs.length;
            out.println("共检測到[" + count + "]个client证书");
            for (int i = 0; i < count; i++) {
                out.println("client证书 [" + (++i) + "]: ");
                out.println("校验结果:" + verifyCertificate(certs[--i]));
                out.println("证书具体:\r" + certs[i].toString());
            }
        } else {
            if (SCHEME_HTTPS.equalsIgnoreCase(request.getScheme())) {
                out.println("这是一个HTTPS请求。可是没有可用的client证书");
                request.setAttribute("user", "username");
                out.println(request.getAttribute("user"));
            } else {
                out.println("这不是一个HTTPS请求,因此无法获得client证书列表 ");

            }
        }
        out.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * <p>
     * 校验证书是否过期
     * </p>
     *
     * @param certificate
     * @return
     */
    private boolean verifyCertificate(X509Certificate certificate) {
        boolean valid = true;
        try {
            certificate.checkValidity();
        } catch (Exception e) {
            e.printStackTrace();
            valid = false;
        }
        return valid;
    }

client代码:

/**
 * Copyright (C) 2011-2014 sgcc Inc.
 * All right reserved.
 * modify info:
 */
package com.sengle.cloud.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpsClient {
    private static final String KEY_STORE_TYPE_TRUST = "jks"; //假设证书为bks格式,那么要改为bks,同一时候以下的KEY_STORE_TYPE_CLIENT也要改为bks
//    private static final String KEY_STORE_TYPE_CLIENT = "PKCS12"; //假设KEY_STORE_TYPE_TRUST为jks,则KEY_STORE_TYPE_CLIENT为PKCS12
    private static final String KEY_STORE_TYPE_CLIENT = "PKCS12"; //假设KEY_STORE_TYPE_TRUST为bks,则此处也应该为bks。
    private static final String SCHEME_HTTPS = "https";
    private static final int HTTPS_PORT = 8443; //此处为tomcat中的配置。默觉得8443
    private static final String HTTPS_URL = "https://10.100.100.24:8443/SSL/sslServlet";

    private static final String basePath = "D:/SSL/";
    private static final String KEY_STORE_CLIENT_PATH = basePath + "/client-24.p12"; //假设为bks,那么此处应该为bks格式的证书
    private static final String KEY_STORE_TRUST_PATH = basePath + "/client-24.truststore"; //假设为bks,那么此处应该为bks格式的证书
    private static final String KEY_STORE_PASSWORD = "123456"; //password
    private static final String KEY_STORE_TRUST_PASSWORD = "123456";  // password

    public static void main(String[] args) throws Exception {
        ssl();
    }

    private static void ssl() throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            KeyStore keyStore  = KeyStore.getInstance(KEY_STORE_TYPE_CLIENT);
            KeyStore trustStore  = KeyStore.getInstance(KEY_STORE_TYPE_TRUST);
            InputStream ksIn = new FileInputStream(KEY_STORE_CLIENT_PATH);
            InputStream tsIn = new FileInputStream(new File(KEY_STORE_TRUST_PATH));
            try {
                keyStore.load(ksIn, KEY_STORE_PASSWORD.toCharArray());
                trustStore.load(tsIn, KEY_STORE_TRUST_PASSWORD.toCharArray());
            } finally {
                try { ksIn.close(); } catch (Exception ignore) {}
                try { tsIn.close(); } catch (Exception ignore) {}
            }
            //双向验证载入keystore和truststore两个证书
            SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, KEY_STORE_PASSWORD, trustStore);

            /*
             * 单向验证,仅仅载入truststore
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            */

            Scheme sch = new Scheme(SCHEME_HTTPS, HTTPS_PORT, socketFactory);
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
            HttpGet httpget = new HttpGet(HTTPS_URL);
            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }
                bufferedReader.close();
            }
            EntityUtils.consume(entity);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}
时间: 2024-10-12 02:57:32

SSL通关之代码演示样例(四)的相关文章

c语言学习之结构篇代码演示样例-输入n个同学的姓名,数学英语成绩,依照平均分从低到高排序并输出

#include<stdio.h> void main(){ const int count = 5;//定义数量 struct student{ char name[80]; float math,eng; float aver; }stu[count],temp; //输入 for (int i = 0; i < count; i++){ scanf("%s%f%f", stu[i].name, &stu[i].math, &stu[i].eng)

Python Web框架Tornado的异步处理代码演示样例

1. What is Tornado Tornado是一个轻量级但高性能的Python web框架,与还有一个流行的Python web框架Django相比.tornado不提供操作数据库的ORM接口及严格的MVC开发模式,但能够提供主要的web server功能.故它是轻量级的:它借助non-blocking and event-driven的I/O模型(epoll或kqueue)实现了一套异步网络库,故它是高性能的. Tornado的轻量级+高性能特性使得它特别适用于提供web api的场合

Linux线程基本使用代码演示样例

#include <pthread.h> #include <stdio.h> #include <unistd.h> void* thread_func(void* param) { const char* p = (const char*)param; pid_t pid = 0; pthread_t tid = 0; pid = getpid(); tid = pthread_self(); printf("%s -> %8u %8u\n"

[Python] SQLBuilder 演示样例代码

用Python写一个SQLBuilder.Java版能够从 http://www.java2s.com/Code/Java/Database-SQL-JDBC/SQLBuilder.htm 看到. 附上代码: 演示样例代码(一): class SQLDirector: @classmethod def buildSQL(cls, builder): sql = "" sql += builder.getCommand() sql += builder.getTable() sql +=

PHPCMS中GET标签概述、 get 标签语法、get 标签创建工具、get 调用本系统演示样例、get 调用其它系统演示样例

一.get 标签概述 通俗来讲,get 标签是Phpcms定义的能直接调用数据库里面内容的简单化.友好化代码,她可调用本系统和外部数据,仅仅有你对SQL有一定的了解,她就是你的绝世好剑!也就是适合熟悉SQL语句的人使用.有了她,我们打造个性化的站点,能很方便的调用出数据库里面指定的内容.通过条件限制,我们能够调用出不同条件下的不同数据. 二.get标签样式 {get dbsource=" " sql=" "} {/get} 三.get 标签语法 1.get标签属性值

Android之——多线程下载演示样例

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/46883927 一.概述 说到Android中的文件下载.Android API中明白要求将耗时的操作放到一个子线程中运行,文件的下载无疑是须要耗费时间的.所以要将文件的下载放到子线程中运行. 以下,我们一起来实现一个Android中利用多线程下载文件的小样例. 二.服务端准备 在这个小样例中我下面载有道词典为例.在网上下载有道词典的安装包,在eclipse中新建项目web.将下载

使用Dropzone上传图片及回显演示样例

一.图片上传所涉及到的问题 1.HTML页面中引入这么一段代码 <div class="row"> <div class="col-md-12"> <form dropzone2 class="dropzone" enctype="multipart/form-data" method="post"></form> </div> </div&

C编程规范, 演示样例代码。

/*************************************************************** *Copyright (c) 2014,TianYuan *All rights reserved. * *文件名: standard.h *文件标识: 编程规范演示样例代码 * *当前版本号:V1.0 *作者:wuyq *完毕日期:20140709 * *改动记录1: //改动历史记录.包含改动日期.版本号号.改动人及改动内容等 *改动日期 版本号号 改动人 改动内

Android模糊演示样例-RenderScript-附效果图与代码

本文链接    http://blog.csdn.net/xiaodongrush/article/details/31031411 參考链接    Android高级模糊技术    http://stackoverflow.com/questions/14879439/renderscript-via-the-support-library 1. 程序截图     拖动红色区域,能够显示出清晰的汽车部分. 拖动以下的滑块,能够更改模糊程度.       watermark/2/text/aHR