实际开发过程中,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();
}
}
}

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

  1. java 覆盖hashCode()深入探讨 代码演示样例

    java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...

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

    1. What is Tornado Tornado是一个轻量级但高性能的Python web框架,与还有一个流行的Python web框架Django相比.tornado不提供操作数据库的ORM接口 ...

  3. Swift语言 简明基础 代码演示样例

    开发环境: Mac.Xcode6.0 下面内容均可创建ios common line项目来測试 1.Hello World演示样例 使用xcode创建新的common line项目,查看主文件main ...

  4. 【甘道夫】Eclipse+Maven搭建HBase开发环境及HBaseDAO代码演示样例

    环境: Win764bit Eclipse Version: Kepler Service Release 1 java version "1.7.0_40" 第一步:Eclips ...

  5. Java中普通代码块,构造代码块,静态代码块的代码演示样例及区分

    //运行顺序:(优先级从高到低.)静态代码块>mian方法>构造代码块>构造方法. 当中静态代码块仅仅运行一次.构造代码块在每次创建对象是都会运行. 1 普通代码块 <span ...

  6. android动画-动画分类及代码演示样例

    原来一直对动画一知半解,仅仅知道依照网上的方法会用即可了,可是自己写起来感觉确实有点费劲,今天最终研究了代码实现,一下子感觉清晰多了.先把总结例如以下,代码中有具体的凝视. 动画分类 1.Peoper ...

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

    #include<stdio.h> void main(){ const int count = 5;//定义数量 struct student{ char name[80]; float ...

  8. Cocos2d-x使用Javascript开发js绑定C++&lt;代码演示样例&gt;

    class IOSiAPDelegate{ public: virtual ~IOSiAPDelegate() {} }; class IOSAlipay{ public: IOSAlipay(); ...

  9. [Python] SQLBuilder 演示样例代码

    用Python写一个SQLBuilder.Java版能够从 http://www.java2s.com/Code/Java/Database-SQL-JDBC/SQLBuilder.htm 看到. 附 ...

随机推荐

  1. 在shell脚本中使用代理

    设置所有的代理走socks5 export ALL_PROXY="socks5://127.0.0.1:1080" 取消代理 unset ALL_PROXY  

  2. Linux安装PHP MongoDB扩展

    本文将讲述一下本人安装MongoDB扩展的过程,大家可以略作参考 安装环境 Linux环境:CentOS 6.5 Apache版本:2.4 PHP版本:5.4.3 MongoDB版本:2.6.5 一. ...

  3. Unity调用Android的两种方式:其一、调用jar包

    unity在Android端开发的时候,免不了要调用Java:Unity可以通过两种方式来调用Android:一是调用jar.二是调用aar. 这篇文章主要讲解怎么从无到有的生成一个jar包,然后un ...

  4. springboot实现热部署,修改代码不用重启服务

    1.引入热部署依赖 <!-- 热部署模块 --> <dependency> <groupId>org.springframework.boot</groupI ...

  5. 【Educational Codeforces Round 37 B】 Tea Queue

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 用一个队列来模拟排队就好. 队列放三元组(x,y,z) x表示人的下标,y和z分别表示进入和退出时间. 然后枚举时间从1到5000 ...

  6. 洛谷 P2005 A/B Problem II

    P2005 A/B Problem II 题目背景 为了让大家紧张的心情放松一下,这一题题是一道非常简单的题目. 题目描述 给出正整数N和M,请你计算N div M(N/M的下取整). 输入输出格式 ...

  7. OpenGL 获取当前屏幕坐标对应的三维坐标

    转自原文 OpenGL 获取当前屏幕坐标对应的三维坐标,使用很简单glu库中的一个函数 #include <GL/glut.h> #include <stdlib.h> #in ...

  8. C++11之decltype

    使用场景 在C++中常常要用到非常长的变量名.假设已经有变量和你将使用的变量是一个类型.就可以使用decltypekeyword 来申明一样的类型变量. decltype原理      返回现有变量类 ...

  9. Jeff Dean专访,有不少干货

    <专访Jeff Dean:我们要推动机器学习再上一层楼> 文件链接如下: Link https://arxiv.org/ 有意思的是,里面提到的 arXiv网站,一个能够用来证明论文上传时 ...

  10. [Poi] Build and Analyze Your JavaScript Bundles with Poi

    Ever wonder where those extra KB in your bundle are coming from? This lesson walks you through runni ...