首页 > 编程 > JSP > 正文

tomcat配置https详述(SSL)

2024-09-05 00:20:43
字体:
来源:转载
供稿:网友

    一般的网页传输都是基于http协议,在网络中流通的信息都为明文,非常容易泄密。为保证网站信息不被中间服务器或者其它探测软件捕获,一般企业都使用 SSL对网页内容加密,下面介绍tomcat中的SSL加密,详细可参考链接:http://tomcat.apache.org/tomcat- 7.0-doc/ssl-howto.html

tomcat的加密根据自身的特色分两种情况,一种为使用Java runtime(非APR),一种为OpenSSL library (through APR/Tomcat-Native). 这两种的配置完全不同,下面分别介绍,读者可以按自己应用的情况分别选择。

一、Java runtime(非APR)情况
  1、产生client /server java key store

import java.io.FileOutputStream;import java.math.BigInteger;import java.security.InvalidKeyException;import java.security.KeyPair;import java.security.KeyStore;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.SecureRandom;import java.security.SignatureException;import java.security.cert.Certificate;import java.security.cert.CertificateEncodingException;import java.security.cert.X509Certificate;import java.util.Date;import javax.security.auth.x500.X500Principal;import javax.security.auth.x500.X500PrivateCredential;import org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator;import org.bouncycastle.x509.X509V3CertificateGenerator;/** *  * Tomcat HTTPS client/server key Certificate generator *  */public class TomcatKey { //Client Certificate static String TRUST_STORE_NAME = "client"; static char[] TRUST_STORE_PASSWORD = "test".toCharArray();  //Server Certificate  static String SERVER_NAME = "server"; static char[] SERVER_PASSWORD = "test".toCharArray(); static String SERVER_HOST = "localhost"; /**  * @param args  */ public static void main(String[] args) {  try {   // trustsotre, my root certificate   KeyStore store = KeyStore.getInstance("JKS");   // initialize   store.load(null, null);   KeyPair rootPair = generateKeyPair();   X500PrivateCredential rootCredential = createRootCredential(rootPair);   store.setCertificateEntry(TRUST_STORE_NAME, rootCredential     .getCertificate());   store.store(new FileOutputStream(TRUST_STORE_NAME + ".keystore"),     TRUST_STORE_PASSWORD);   // server credentials   store = KeyStore.getInstance("JKS");   store.load(null, null);   store.setKeyEntry(SERVER_NAME, rootCredential.getPrivateKey(),     SERVER_PASSWORD, new Certificate[] { rootCredential       .getCertificate() });   store.store(new FileOutputStream(SERVER_NAME + ".keystore"),     SERVER_PASSWORD);  } catch (NoSuchAlgorithmException e) {   e.printStackTrace();  } catch (NoSuchProviderException e) {   e.printStackTrace();  } catch (Exception e) {   e.printStackTrace();  } } //generate Key Pair public static KeyPair generateKeyPair() throws NoSuchAlgorithmException,   NoSuchProviderException {  // create the keys  java.security.KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");  generator.initialize(1024, new SecureRandom());  return generator.generateKeyPair(); } //generate certificate public static X500PrivateCredential createRootCredential(KeyPair rootPair) throws Exception {  X509Certificate rootCert = generateX509V3RootCertificate(rootPair);  return new X500PrivateCredential(rootCert, rootPair.getPrivate()); }  public static X509Certificate generateX509V3RootCertificate(KeyPair pair)throws NoSuchAlgorithmException,  NoSuchProviderException, CertificateEncodingException, InvalidKeyException, IllegalStateException, SignatureException {    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));    certGen.setIssuerDN(new X500Principal("CN=" + SERVER_HOST+ ", OU=GoldenSF, O=SHA, C=cn"));    certGen.setNotBefore(new Date(System.currentTimeMillis() - 5000L));    certGen.setSubjectDN(new X500Principal("CN=" + SERVER_HOST+ ", OU=GoldenSF, O=SHA, C=cn"));    certGen.setPublicKey(pair.getPublic());    certGen.setSignatureAlgorithm("SHA1WithRSA");    certGen.setNotAfter(new Date(System.currentTimeMillis() + Integer.MAX_VALUE));    return certGen.generate(pair.getPrivate(), new SecureRandom());   }}

2、将产生的文件:client.keystore, and server.keystore放到apache-tomcat-7/conf下面

  3、修改/conf/server.xml如下:

<?xml version='1.0' encoding='utf-8'?><Server port="8005" shutdown="SHUTDOWN">    <!--<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />  -->  <Listener className="org.apache.catalina.core.JasperListener" />  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />  <GlobalNamingResources>    <Resource name="UserDatabase" auth="Container"              type="org.apache.catalina.UserDatabase"              description="User database that can be updated and saved"              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"              pathname="conf/tomcat-users.xml" />  </GlobalNamingResources>  <Service name="Catalina">		<Connector port="443" SSLEnabled="true"                maxThreads="150" scheme="https" secure="true"                clientAuth="false" sslProtocol="TLS" 			                  keystoreFile="conf/server.keystore" keystorePass="test" 			  truststoreFile ="conf/client.keystore" truststorePass="test"/> 	<Connector port="8009" enableLookups="false" redirectPort="443" protocol="AJP/1.3" />    	    <Engine name="Catalina" defaultHost="localhost">          <Realm className="org.apache.catalina.realm.LockOutRealm">            <Realm className="org.apache.catalina.realm.UserDatabaseRealm"               resourceName="UserDatabase"/>      </Realm>      <Host name="localhost"  appBase="webapps"            unpackWARs="true" autoDeploy="true">        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"                 prefix="localhost_access_log." suffix=".txt"               pattern="%h %l %u %t &quot;%r&quot; %s %b" resolveHosts="false"/>      </Host>    </Engine>  </Service></Server>

4、启动tomcat, 如果 https://localhost/ 能正常打开,说明配置成功。

一些注意:
  1)如果不使用JAVA文件生成keystore,也可以通过JDK自带的命令生成,
    如生成服务器端证书 keytool -genkey -keyalg RSA -dname "cn=localhost,ou=test,o=test,l=hongkong,st=hk,c=hk" -alias server -keypass asdfzxcv23 -keystore server.jks -storepass asdfzxcv23 -validity 3650 客户端的CN可以是任意值,具体的可以参考相关文章
  2)在修改server.xml时,需要将tomcat的默认APR配置删除
  <!--<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />  -->
  3)如果之前有APR的配置,需要删除文件bin/tcnative-1.dll
  4)注意JAVA文件生成的key和密码一定要与配置中的一致,区分大小写。


二、OPENSSL library (through APR/Tomcat-Native)情况
  1、首先需要到OPENSSL网站下载OpenSSL-Win32(或者Linux),安装非常简单
  2、利用OPENSSL生成公钥
    D:/OpenSSL-Win32/bin>openssl
   genrsa -des3 -out key1.pem 2048

  enter pwd: test, to get a file : key1.pem

  3、继续利用OPENSSL生成私钥
   req -new -x509 -key key1.pem -out key1cert.pem -days 1095

   得到文件: key1cert.pem

  4、将这两个文件放到apache-tomcat-7/conf目录下,并修改server.xml为如下内容:

<?xml version='1.0' encoding='utf-8'?><Server port="8005" shutdown="SHUTDOWN">    <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />  <Listener className="org.apache.catalina.core.JasperListener" />  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />  <GlobalNamingResources>    <Resource name="UserDatabase" auth="Container"              type="org.apache.catalina.UserDatabase"              description="User database that can be updated and saved"              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"              pathname="conf/tomcat-users.xml" />  </GlobalNamingResources>    <Service name="Catalina">		<Connector port="443" maxHttpHeaderSize="8192"			maxThreads="150" minSpareThreads="25" 			enableLookups="false" disableUploadTimeout="true"			acceptCount="100" scheme="https" secure="true"			clientAuth="false" 			SSLEnabled="true"			protocol="org.apache.coyote.http11.Http11AprProtocol"			SSLCertificateFile="D:/apache-tomcat-7/conf/key1cert.pem"			SSLCertificateKeyFile="D:/apache-tomcat-7/conf/key1.pem"			SSLPassword="test"		/>					 		<Connector port="8009" enableLookups="false" redirectPort="443" protocol="AJP/1.3" />    	    <Engine name="Catalina" defaultHost="localhost">          <Realm className="org.apache.catalina.realm.LockOutRealm">            <Realm className="org.apache.catalina.realm.UserDatabaseRealm"               resourceName="UserDatabase"/>      </Realm>      <Host name="localhost"  appBase="webapps"            unpackWARs="true" autoDeploy="true">        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"                 prefix="localhost_access_log." suffix=".txt"               pattern="%h %l %u %t &quot;%r&quot; %s %b" resolveHosts="false"/>      </Host>    </Engine>  </Service></Server>

  5、启动tomcat ,https://localhost如果能正常打开,说明配置成功。

  几点注意:
      1)、注意APR是否已经正常配置,
      2)、在启动tomcat前需要确认任务管理器中没有其它tomcat进程在执行(一般删除所有javaw.exe即可),免得造成冲突,提示:java.lang.Exception: Socket bind failed;
      3)、密码要一致,文件名不可写混。

以上是我在tomcat环境下配置HTTPS的一点心得,欢迎大家指正。

http://zeallf.javaeye.com/blog/833250

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表