`
sb33060418
  • 浏览: 150099 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

数字证书及安全加密(二)tomcat单向SSL验证及服务调用

阅读更多
本篇博文内容包括:tomcat单/双向SSL验证配置及使用java程序访问https服务。
文中涉及证书和安全的知识请参考上一篇:数字证书及安全加密(一)数字证书基础知识http://sb33060418.iteye.com/admin/blogs/1998862

系统环境:
windows+jdk1.6.0_31+tomcat6.0+httpclient4.3.1

单向SSL配置
1.生成服务端证书
cd %JAVA_HOME%/bin
keytool -genkey -v -alias server -keyalg RSA -keystore D:/lib/server.keystore -storepass server

创建了别名为server的证书(jks类型),文件名为server.keystore,密码为server,密钥算法为RSA。
生成时需要输入多项证书信息,因不影响本次时间测试,不在此展示。

    配置dns
编辑C:\Windows\System32\drivers\etc\hosts文件,在文件最后加上server的地址。
127.0.0.1 server


2.配置tomcat
配置tomcat/conf/server.xml,打开注释或加入以下配置
<Connector protocol="org.apache.coyote.http11.Http11NioProtocol"  
     port="8443" minSpareThreads="5" maxSpareThreads="75"  
     enableLookups="true" disableUploadTimeout="true"    
     acceptCount="100"  maxThreads="200"  
     scheme="https" secure="true" SSLEnabled="true"  
     clientAuth="false" sslProtocol="TLS"  
     keystoreFile="D:/lib/server.keystore"    
     keystorePass="server"/>

配置中使用Http11NioProtocol协议和8443端口,sslProtocol为TLS,clientAuth为false表示不要求客户端使用SSL认证,证书库文件/密码为上一步骤生成的服务端证书库。

重启tomcat后,使用http://server:8080/https://server:8443/都可以访问tomcat下应用,但是浏览器会提示不可信的证书(只有使用受信任的根证书发出证书才不会提示)。

3.配置应用路径
上一步配置后,tomcat/webapps目录下的应用的所有路径都可以被http/https访问。可以通过对单个应用的配置,使得该应用下的某些路径只能使用https访问。
    a.普通web应用
对于普通web应用,需要在web.xml加入以下配置:
<!-- ssl -->
<security-constraint>
  <web-resource-collection>
      <web-resource-name>securedapp</web-resource-name>
      <url-pattern>/rest/**</url-pattern>
  </web-resource-collection>
  <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  </user-data-constraint>

重新部署应用后,/rest/下所有路径只能使用https访问。

    b.spring security应用
对于使用了spring security框架的应用,不需要配置web.xml,只需要在applicationContext-security.xml的<http></http>标签中加入以下配置并重新部署。
<intercept-url pattern="/rest/**" requires-channel="https">


4.httpclient访问
经过上面的配置后,使用浏览器可以访问https服务(提示不受信任的网站证书)。使用java访问时会报unable to find valid certification path to requested target(不受信任)或java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty(客户端信任库为空)异常,因为httpclient不信任该证书。

    a.信任自签发证书
可以在java代码里设置相信自身签发的证书,就可以访问本地的https服务了。使用httpclient代码如下:
package test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.DefaultHttpClient;

public class TestServerSSL {

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the arguments
	 */
	public static void main(String[] args) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			// 信任自身签发证书
			SSLSocketFactory socketFactory = new SSLSocketFactory(
					new TrustSelfSignedStrategy());
			Scheme sch = new Scheme("https", socketFactory, 8443);
			httpclient.getConnectionManager().getSchemeRegistry().register(sch);
			HttpGet httpget = new HttpGet(
					"https://server:8443/api/rest/test");
			System.out.println("executing request" + httpget.getRequestLine());
			HttpResponse response = httpclient.execute(httpget);
			System.out.println("-------------response-------------");
			System.out.println(response.getStatusLine());
			HttpEntity entity = response.getEntity();
			System.out.println(EntityUtils.toString(response.getEntity()));			if (entity != null) {
				entity.consumeContent();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();

	}

}

运行后可以看到httpclient从本地服务端取回的数据。

    b.信任所有证书
如果希望程序不仅仅只是信任自签发证书,也可以信任其他所有证书,可以将
			// 信任自身签发证书
			SSLSocketFactory socketFactory = new SSLSocketFactory(
					new TrustSelfSignedStrategy());

替换为
			// 信任所有证书
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
				}

				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext);

这样程序就能信任其他证书签发机构签发的证书了。

    c.主机名校验
但httpclient只能连接至https://server:8443/而不能访问localhost、127.0.0.1或本地ip,否则抛出异常
  • javax.net.ssl.SSLException: hostname in certificate didn't match: <127.0.0.1> != <server>

可以在代码中允许SSL连接至任意主机名标示符,加入下行代码即可
			socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

当然这段代码导致程序极不安全,因为可能证书被其他网站使用,证书的名称和网站域名不一致。

配置信任证书库
但上面的代码并不能限定程序只信任我们刚生成的server证书。
如果java程序访问此地址时在jre默认的信任库中找不到对方证书的颁发机构,则会抛出安全方面的异常。所以要将站方公钥存进一个信任证书库,并在环境变量中设定,表明信任此库中的公钥,才可以正常访问。

5.导出服务端证书
keytool -export -v -alias server -keystore D:/lib/server.keystore -rfc -file D:/lib/server.cer -storepass server

或:点击地址栏https》证书信息》详细信息》复制到文件》下一步》DER编码二进制X.509(.cer)》选择目录及文件名》确认

6.导入服务端证书至客户端信任库
keytool -import -v -alias server -file D:/lib/server.cer -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -storepass server



7.使用信任证书库
将socketFactory替换为以下代码
			// trustStore
			System.out.println("---trustStore---");
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());
			FileInputStream instream = new FileInputStream(
					// 信任库路径
					new File(	"D:/Program Files (x86)/Java/jdk1.6.0_31/jre/lib/security/cacerts"));
			try {
				// 证书库密码
				trustStore.load(instream, "server".toCharArray());
			} finally {
				instream.close();
			}
			Enumeration<String> e = trustStore.aliases();
			while (e.hasMoreElements()) {
				System.out.println(e.nextElement());
			}
			SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);

程序会读取上一步导入的信任库来建立SSL链接。在控制台可以看到证书库中包含的证书别名。

8.web应用
web应用在服务器启动时,会自动读取jdk默认的证书库来访问https服务。

使用spring security oauth2框架,通过https协议来访问rest服务时,通过上述配置步骤可以验证通过。




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics