转自:http://gezhicheng.iteye.com/blog/747973
在web应用交互过程中,有很多场景需要保证通信数据的安全;在前面也有好多篇文章介绍了在Web Service调用过程中用WS-Security来保证接口交互过程的安全性,值得注意的是,该种方式基于的传输协议仍然是Http,采用这种方式可扩 展性和数据交互效率比较高;另外一种实现方式就是用Https,他是在协议层对Http的再次封装,加入了SSL/TLS,采用该协议进行通信的数据全部 都会被加密,由于目前Web开发编程中对此都有了一定程度的封装,所以采用Https对外提供服务,除了证书以外,对编程能力的要求并不高,相对于前者门 槛较低,但是由于对双方通信的所有数据都进行加密,而且交互过程中还有多次握手等,所以效率较低;以下就介绍下在Java中访问Https链接时会出现的 一些问题;
在Java中要访问Https链接时,会用到一个关键类HttpsURLConnection;参见如下实现代码:
Java代码
// 创建URL对象
URL myURL = new URL("https://www.sun.com");
// 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
HttpsURLConnection httpsConn = (HttpsURLConnection) myURL
.openConnection();
// 取得该连接的输入流,以读取响应内容
InputStreamReader insr = new InputStreamReader(httpsConn
.getInputStream());
// 读取服务器的响应内容并显示
int respInt = insr.read();
while (respInt != -1) {
System.out.print((char) respInt);
respInt = insr.read();
}
在取得connection的时候和正常浏览器访问一样,仍然会验证服务端的证书是否被信任(权威机构发行或者被权威机构签名);如果服务端证书不被信任,则默认的实现就会有问题,一般来说,用SunJSSE会抛如下异常信息:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
上面提到SunJSSE,JSSE(Java Secure Socket Extension)是实现Internet安全通信的一系列包的集合。它是一个SSL和TLS的纯Java实现,可以透明地提供数据加密、服务器认证、 信息完整性等功能,可以使我们像使用普通的套接字一样使用JSSE建立的安全套接字。JSSE是一个开放的标准,不只是Sun公司才能实现一个 SunJSSE,事实上其他公司有自己实现的JSSE,然后通过JCA就可以在JVM中使用。
关于JSSE的详细信息参考官网Reference:http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html;
以及Java Security Guide:http://java.sun.com/j2se/1.5.0/docs/guide/security/;
在深入了解JSSE之前,需要了解一个有关Java安全的概念:客户端的TrustStore文件。客户端的TrustStore文件中保存着被客 户端所信任的服务器的证书信息。客户端在进行SSL连接时,JSSE将根据这个文件中的证书决定是否信任服务器端的证书。在SunJSSE中,有一个信任 管理器类负责决定是否信任远端的证书,这个类有如下的处理规则:
1、若系统属性javax.net.sll.trustStore指定了TrustStore文件,那么信任管理器就去jre安装路径下的lib/security/目录中寻找并使用这个文件来检查证书。
2、若该系统属性没有指定TrustStore文件,它就会去jre安装路径下寻找默认的TrustStore文件,这个文件的相对路径为:lib/security/jssecacerts。
3、若jssecacerts不存在,但是cacerts存在(它随J2SDK一起发行,含有数量有限的可信任的基本证书),那么这个默认的TrustStore文件就是lib/security/cacerts。
那遇到这种情况,怎么处理呢?有以下两种方案:
1、按照以上信任管理器的规则,将服务端的公钥导入到jssecacerts,或者是在系统属性中设置要加载的trustStore文件的路径;证书导入可以用如下命令:keytool -import -file src_cer_file –keystore dest_cer_store;至于证书可以通过浏览器导出获得;
2、实现自己的证书信任管理器类,比如MyX509TrustManager,该类必须实现X509TrustManager接口中的三个method;然后在HttpsURLConnection中加载自定义的类,可以参见如下两个代码片段,其一为自定义证书信任管理器,其二为connect时的代码:
Java代码
package test;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
/*
* The default X509TrustManager returned by SunX509. We'll delegate
* decisions to it, and fall back to the logic in this class if the
* default X509TrustManager doesn't trust it.
*/
X509TrustManager sunJSSEX509TrustManager;
MyX509TrustManager() throws Exception {
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("trustedCerts"),
"passphrase".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) {
sunJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
// do any special handling here, or rethrow exception.
}
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the
* cert chain.
*/
}
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return sunJSSEX509TrustManager.getAcceptedIssuers();
}
}
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
// 创建URL对象
URL myURL = new URL("https://ebanks.gdb.com.cn/sperbank/perbankLogin.jsp");
// 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
httpsConn.setSSLSocketFactory(ssf);
// 取得该连接的输入流,以读取响应内容
InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());
// 读取服务器的响应内容并显示
int respInt = insr.read();
while (respInt != -1) {
System.out.print((char) respInt);
respInt = insr.read();
}
对于以上两种实现方式,各有各的优点,第一种方式不会破坏JSSE的安全性,但是要手工导入证书,如果服务器很多,那每台服务器的JRE都必须做相同的操作;第二种方式灵活性更高,但是要小心实现,否则可能会留下安全隐患;
分享到:
相关推荐
NULL 博文链接:https://forlan.iteye.com/blog/2404071
使用httpclient和httpsurlconnection两种方法访问https网址,同时分为验证证书和不验证证书两种方法
主要介绍了Java下载https文件并上传到阿里云oss服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
NULL 博文链接:https://410063005.iteye.com/blog/1751366
Android使用HttpClient和HttpsUrlConnection两种方式访问https网站
项目里包含一个访问tomcat 的https连接和访问普通url(www.google.com)的https连接 一定记得配置tomcat支持https 配置过程很容易 我的博客转载了方法 还有亲测jdk1.7 tomcat7.0可以
本demo使用HttpsURLConnection方式的SSL双向认证,实现oauth2.0客户端请求方式,并且实现了普通post接口请求,及多图上传的post请求接口,做了网络请求的封装。
主要介绍了JAVA通过HttpURLConnection 上传和下载文件的方法,非常具有实用价值,需要的朋友可以参考下
android studio实现HttpsURLConnection post请求的发送并接收
URL url = new URL( "https://localhost:8443"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod( "POST"); connection.setDoOutput(true); ...
HttpsURLConnection-Post 使用HttpURLConnection的发布方法
本类可以用来访问https连接,带cookie的连接,重定向的连接,基于HttpsUrlConnection,不需要第三方库
HttpsUrlConnection android网络请求类 当然还有HttpUrlConnection对应http请求,下面以百度首页为例进行请求 写一个GET请求工具类 public class NetUtlis { public static String SendUrlRequest(String s){ ...
用PD4ML把HTML转pdf,下载可以直接运行,包含了所需要的jar包,其中有我找了好久的页眉页脚,尤其是每页的页数显示,合成时插入图片等功能,需要的可以下载
下面小编就为大家带来一篇HttpsURLConnection上传文件流(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
现在很多主流平台采用rest方式的...于是乎简单封装下rest请求api(其实就是两个简单Java类,呵呵),可以实现http及https模式的请求,也支持JsessionId和代理模式,甚至系统自动发送邮件的功能也是用此工具类实现的.
Barzahlen付款模块Java SDK(v2.0.1) 弃用通知 此SDK已不再维护,不应用于新项目。 将来可能会有更新的版本支持我们的 。...如果要使用除HttpsURLConnection以外的其他HttpClient,则可以创建自己的并实现HttpClie
导语:个人对网络连接接触的不多,在使用时自己发现一些问题,记录一下。 正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是IOException错误,responseCode = -1。一直想不明白,同一个程序我调用...
import javax.net.ssl.HttpsURLConnection ; import javax.net.ssl.SSLContext ; import javax.net.ssl.SSLSocketFactory ; import java.net.URL ; import com.aliyun.gmsse.GMProvider ; public class Main