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();
}
}
}
SSL通关之代码演示样例(四)的更多相关文章
- java 覆盖hashCode()深入探讨 代码演示样例
java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...
- Python Web框架Tornado的异步处理代码演示样例
1. What is Tornado Tornado是一个轻量级但高性能的Python web框架,与还有一个流行的Python web框架Django相比.tornado不提供操作数据库的ORM接口 ...
- Swift语言 简明基础 代码演示样例
开发环境: Mac.Xcode6.0 下面内容均可创建ios common line项目来測试 1.Hello World演示样例 使用xcode创建新的common line项目,查看主文件main ...
- 【甘道夫】Eclipse+Maven搭建HBase开发环境及HBaseDAO代码演示样例
环境: Win764bit Eclipse Version: Kepler Service Release 1 java version "1.7.0_40" 第一步:Eclips ...
- Java中普通代码块,构造代码块,静态代码块的代码演示样例及区分
//运行顺序:(优先级从高到低.)静态代码块>mian方法>构造代码块>构造方法. 当中静态代码块仅仅运行一次.构造代码块在每次创建对象是都会运行. 1 普通代码块 <span ...
- android动画-动画分类及代码演示样例
原来一直对动画一知半解,仅仅知道依照网上的方法会用即可了,可是自己写起来感觉确实有点费劲,今天最终研究了代码实现,一下子感觉清晰多了.先把总结例如以下,代码中有具体的凝视. 动画分类 1.Peoper ...
- c语言学习之结构篇代码演示样例-输入n个同学的姓名,数学英语成绩,依照平均分从低到高排序并输出
#include<stdio.h> void main(){ const int count = 5;//定义数量 struct student{ char name[80]; float ...
- Cocos2d-x使用Javascript开发js绑定C++<代码演示样例>
class IOSiAPDelegate{ public: virtual ~IOSiAPDelegate() {} }; class IOSAlipay{ public: IOSAlipay(); ...
- [Python] SQLBuilder 演示样例代码
用Python写一个SQLBuilder.Java版能够从 http://www.java2s.com/Code/Java/Database-SQL-JDBC/SQLBuilder.htm 看到. 附 ...
随机推荐
- 远程登录工具 —— filezilla(FTP vs. SFTP)、xshell、secureCRT
filezilla:是一个免费开源的 FTP 软件,分为客户端版本和服务器版本,具备所有的 FTP 软件功能. 支持的协议:FTP & SFTP(Secure File Transfer Pr ...
- POJ 3672 水题......
5分钟写完 水水更开心 //By SiriusRen #include <cstdio> #include <iostream> #include <algorithm& ...
- C# HashSet<T> 简单使用
一个简单的HashSet<T> 的例子,介绍其简单的方法,深入学习可参考微软:https://msdn.microsoft.com/en-us/library/bb359438(v=vs. ...
- hiho147周 - 数据结构 bitset
题目链接 n个5维数,对于每个数,输出小于他的数的个数(每个维度都比他小); #include <cstdio> #include <cstring> #include < ...
- Git强制覆盖master分支
在开发中,通常会保持两个分支master分支和develop分支,但是如果因为develop上面迭代太多而没有及时维护master,最后想丢弃master而直接将测试确认过的develop强推到mas ...
- 字符串匹配:KMP
參考:从头到尾彻底理解KMP 在字符串 str 中 匹配模式串 pattern 1. 计算模式串的 next 数组: 2. 在字符串中匹配模式串:当一个字符匹配时,str[i++], pattern[ ...
- iOS xib View宽高不能改变
IOS - xib(Interface Builder,view) - can't change view size(view不能改变大小问题) 今天在试着swift语言写个demo,,当中遇到了这个 ...
- hadoop集群中动态添加新的DataNode节点
集群中现有的计算能力不足,须要另外加入新的节点时,使用例如以下方法就能动态添加新的节点: 1.在新的节点上安装hadoop程序,一定要控制好版本号,能够从集群上其它机器cp一份改动也行 2.把name ...
- HDU 5889 Barricade (Dijkstra+Dinic)
思路: 首先 先Dijkstra一遍 找出来最短路 不是最短路上的边都不要 然后呢 套个Dinic模板就好了-- 求个最小割 输出 大功告成~~ //By SiriusRen #include < ...
- Json 序列化以及反序列化的三种方式(二)
1.什么是JSON? Json[javascript对象表示方法],它是一个轻量级的数据交换格式,我们可以很简单的来读取和写它,并且它很容易被计算机转化和生成,它是完全独立于语言的 2.Json支持下 ...