1.生成根证书、服务端证书、客户端证书
1.1 生成CA根证书
生成跟证书私钥root_private.key
openssl genrsa -out root_private.key 1024
(私钥中包含附加信息,可推到出公钥。使用私钥生成的证书包含对应公钥)
生成根证书签发请求文件root.csr
openssl req -new -key root_private.key -out root.csr -subj "/C=CN/ST=GuangDong/L=ShenZhen/O=Test company/OU=Test company/CN=Test company"
生成X.509格式的CA根证书root.crt
openssl x509 -req -days 365 -in root.csr -out root.crt -signkey root_private.key
根据root.crt证书生成truststore JKS文件root.truststore,输入秘钥库密码123456。
这一步只针对双向认证,单向不需要。
keytool -keystore root.truststore -import -trustcacerts -file root.crt
输入yes,信任此证书。
1.2 使用根证书签发服务端证书
(正常是先签发二级证书,由二级证书对服务端签发)
生成服务端私钥文件server_private.key
openssl genrsa -out server_private.key 1024
签名请求文件server.csr
openssl req -new -key server_private.key -out server.csr -subj "/C=CN/ST=GuangDong/L=ShenZhen/O=test-server/OU=test-server/CN=test-server"
使用根证书签发服务端证书server.crt
openssl x509 -req -days 365 -sha1 -CA root.crt -CAkey root_private.key -CAserial ca.srl -CAcreateserial -in server.csr -out server.crt
查看证书信息
openssl x509 -in server.crt -text -noout
将服务端证书转换为pkcs12格式,密码123456
openssl pkcs12 -export -in server.crt -inkey server_private.key -out server.p12
生成服务端秘钥库server.keystore,秘钥库密码也为123456
keytool -importkeystore -srckeystore server.p12 -destkeystore server.keystore -srcstoretype pkcs12
查看keystore
keytool -list -v -keystore server.keystore
1.3 使用根证书签发客户端证书
生成客户端私钥文件client_private.key
openssl genrsa -out client_private.key 1024
签名请求文件client.csr
openssl req -new -key client_private.key -out client.csr -subj "/C=CN/ST=GuangDong/L=ShenZhen/O=test-client/OU=test-client/CN=test-client"
使用根证书签发客户端证书client.crt
openssl x509 -req -days 365 -sha1 -CA root.crt -CAkey root_private.key -CAserial ca.srl -CAcreateserial -in client.csr -out client.crt
证书转换为pkcs12格式,密码123456
以上生成的公私钥和证书都是PEM格式的,服务端、浏览器一般使用PKCS12格式。
openssl pkcs12 -export -in client.crt -inkey client_private.key -out client.p12
查看证书信息
openssl x509 -in client.crt -text -noout
openssl pkcs12 -in client.p12 -info
2.校验自签发证书:单向和双向
2.1 访问CA中心颁发证书的网站
知名CA中心的证书都会预制到系统或浏览器中,无需特别处理,会自行查询验证。例如百度使用的证书,就是CA中心颁发的,如下三行代码即可实现访问。
URL url = new URL("https://www.baidu.com");
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
2.2 本机搭建tomcat服务,用于https服务端验证
从http://tomcat.apache.org下载压缩包解压,执行bin目录下的startup.bat
(使用tomcat7,最新tomcat9的配置有改变,资料较少)
启动成功后,在浏览器输入http://localhost:8080出现tomcat界面表示成功
2.3 自签证书的校验:单向验证
单向验证一般指客户端校验服务端证书,服务端并不检查客户端证书。
自签证书没有在系统中预制&