一 生成客户端证书和服务器端证书。
需要使用keytool工具,第一步先进入到jdk的bin目录下:
先移动到D:\Java\jdk1.7.0\bin目录下 ,再用命令行命令打开,即可使用keytool工具。
1、为服务器生成证书tomcat.keystore 命令中如果是ip方式访问用-ext SAN=ip:xxx.xxx.xx.xx,如果是域名则用 -ext SAN=dns:www.xxx.com,注意"您的名字与姓氏是什么?"就是你的ip或域名。
keytool -genkey -v -alias tomcat -keyalg RSA -ext SAN=ip:xxx.xxx.xx.xx -validity 36500 -keystore tomcat.keystore (以下生成文件均保存在bin目录下)
2、为客户端生成证书,双向认证时需要客户端安装该证书,等待第四步成功后将该证书添加到“个人”区域。
keytool -genkey -v -alias mykey -keyalg RSA -validity 36500 -storetype PKCS12 -keystore client.p12
3、将p12文件导出为一个cer文件,因为不能直接将PKCS12格式的证书库导入服务端证书(tomcat.keystore),storepass 是密码为前面生成证书时,输入的密码123456。
keytool -export -alias mykey -keystore client.p12 -storetype PKCS12 -storepass 123456 -rfc -file client.cer
4、让服务器信任客户端证书。
keytool -import -v -file client.cer -keystore tomcat.keystore
5、查看服务器的证书库。(一个是服务器证书,一个是受信任的客户端证书),可以省略。
keytool -list -keystore tomcat.keystore
6、把服务器证书导出为cer文件,然后将该证书添加到“受信任的根证书颁发机构”区域。
keytool -keystore tomcat.keystore -export -alias tomcat -file server.cer
操作完成,在tomcat的server.xml中配置方法如下: 单向认证时需将clientAuth=“false”,双向时设置为clientAuth=“true”,https的默认端口为443,所以port=“443”,当然也可以设置为其他的。
完成上面6步会在bin目录下生成四个文件
二 改造Tomcat
在Tomcat的conf的server.xml文件中修改:将注销的这一个部分解除注销并修改(或者直接粘贴下面代码);在将tomcat.keystore复制到conf目录下,或者写绝对路径,keystoreFile指的就是文件,keystorePass指的就是密码
<Connector port="8443"
protocol="org.apache.coyote.http11.Http11Protocol"
maxThreads="150" SSLEnabled="true" scheme="https"
secure="true" clientAuth="false" sslProtocol="TLS"
keystoreFile="conf/tomcat.keystore"
keystorePass="123456"
truststoreFile="conf/tomcat.keystore"
truststorePass="123456"
/>
修改Tomcat中conf的web文件:
<!--强制使用https,http请求会自动转为https -->
<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>Client Cert Users-only Area</realm-name>
</login-config>
<!--配置网站支持https,/* 表示全部请求都走https, transport-guarantee 标签设置为 CONFIDENTIAL以便使应用支持 SSL。 如果需要关闭 SSL ,将 CONFIDENTIAL 改为 NONE 即可 -->
<security-constraint>
<web-resource-collection>
<web-resource-name>SSL</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
三 导入证书到服务器端
将 server.cer 导入到浏览器“受信任的根证书颁发机构”区域,这样是为了让浏览器信任服务器。
将 client.p12 导入到浏览器“个人”区域,这样是为了让服务器信任浏览器,访问时会提示选择这个证书。
原文链接:https://blog.csdn.net/u014415844/article/details/137106851