Tomcat下HTTPS双向认证配置以及客户端调用案例
1:生成服务器端的keystore和truststore文件
(1)以jks格式生成服务器端包含Public key和Private Key的keystore文件
keytool -genkey -alias qdssfw -keystore serverKeystore.jks -keypass qdssfw -storepass qdssfw -keyalg RSA -keysize 2048 -validity 3650 -v -dname "CN = qdssfw,O = WZH,DC = WZH,DC = WZH,OU = WZH"
注意:CN的值必须与SSL客户端要连接的SSL服务器的主机名一致。
(2)从keystore中导出别名为server的服务端证书
keytool -export -alias server -keystore serverKeystore.jks -storepass qdssfw -file server.cer
(3)将 server.cer导入客户端的信任证书库clientTruststore.jks
keytool -import -alias trustServer -file server.cer -keystore clientTruststore.jks -storepass qdssfw
2:生成客户端的keystore和truststore文件
(1)以jks格式生成服务器端包含Public key和Private Key的keystore文件
keytool -genkey -alias client -keystore clientKeystore.jks -keypass qdssfw -storepass qdssfw -keyalg RSA -keysize 2048 -validity 3650 -v -dname "CN = qdssfw,O = WZH,DC = WZH,DC = WZH,OU = WZH"
(2) 从keystore中导出别名为client的客户端证书.
keytool -export -alias client -keystore clientKeystore.jks -storepass qdssfw -file client.cer
(3)将client.cer导入服务端的信任证书库serverTruststore.jks
keytool -import -alias trustClient -file client.cer -keystore serverTruststore.jks -storepass qdssfw
3:证书信息
服务器端: serverKeystore.jks serverTruststore.jks
客户端: clientKeystore.jks clientTruststore.jks
4:测试
(1)Tomcat服务器端配置双向HTTPS认证
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="true" sslProtocol="TLS"
keystoreFile="keystore/serverKeystore.jks" keystorePass="qdssfw"
truststoreFile="keystore/serverTruststore.jks" truststorePass="qdssfw"/>
(2)Java客户端访问
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream keyStoreIn = new FileInputStream(new File("C:\\ca2\\clientKeystore.jks"));
FileInputStream trustStoreIn = new FileInputStream(new File("C:\\ca2\\clientTruststore.jks"));
try {
keyStore.load(keyStoreIn, "qdssfw".toCharArray());
trustStore.load(trustStoreIn, "qdssfw".toCharArray());
} finally {
keyStoreIn.close();
trustStoreIn.close();
}
SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, "qdssfw", trustStore);
Scheme sch = new Scheme("https", socketFactory, 8443);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
HttpGet httpget = new HttpGet("https://qdssfw:8443/test02/TestServlet");
System.out.println("Request:" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(readResponseBody(entity.getContent()));
}
if (entity != null) {
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
备注:修改host文件增加:127.0.0.1qdssfw