前言
该文为2个springboot工程开启进行SSL进行交互的认证步骤
一、认证步骤
1、 为服务器生成证书
keytool -genkey -v -alias testServer -keyalg RSA -keystore E:\ssl\testServer.p12 -validity 36500
2、 为客户端生成证书
keytool -genkey -v -alias testClient -keyalg RSA -storetype PKCS12 -keystore E:\ssl\testClient.p12 -validity 36500
3、 将客户端证书导出为CER文件
keytool -export -alias testClient -keystore E:\ssl\testClient.p12 -storetype PKCS12 -storepass 123456 -rfc -file E:\ssl\testClient.cer
4、 将客户端CER文件导入到服务器的证书库
keytool -import -v -file E:\ssl\testClient.cer -keystore E:\ssl\testServer.p12
5、 把服务器证书导出为CER文件
keytool -keystore E:\ssl\testServer.p12 -export -alias testServer -file E:\ssl\testServer.cer
6、 将CER文件导入到服务器的证书库
keytool -import -v -file E:\ssl\testServer.cer -keystore E:\ssl\testClient.p12
7、 工程修改
将p12格式的证书放入各自工程的resource目录下,(在 ***工程配置***和***代码修改***后)执行maven clean(必要!),maven install重新打包或部署。
异常处理
出现SunCertPathBuilderException: unable to find valid certification path to requested target异常时,将证书导入到C:\Program Files\Java\jdk1.8.0_91\jre\lib\security\cacerts
执行:
keytool.exe -importcert -file E:/ssl/xxx.keystore(or p12) -keystore cacerts -storepass 123456
二、工程配置
yaml配置
server:
ssl:
key-store: classpath:testServer.p12(服务端为testClient)
key-store-password: 123456
key-password: 123456
key-alias: testClient
key-store-type: JKS
client-auth: need
trust-store-type: JKS
trust-store-provider: SUN
trust-store: classpath:testServer.p12(服务端为testClient)
trust-store-password: 123456
三、代码修改
client和server的启动类增加以下静态代码块:
client和server的启动类增加以下静态代码块:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class TestApplication {
final static String KEYSTORE_PASSWORD = "123456";
static
{
System.setProperty("javax.net.ssl.trustStore",
TestApplication.class.getClassLoader().getResource("pushServer.p12").getFile());
System.setProperty("javax.net.ssl.trustStorePassword", KEYSTORE_PASSWORD);
System.setProperty("javax.net.ssl.keyStore",
TestApplication.class.getClassLoader().getResource("pushServer.p12").getFile());
System.setProperty("javax.net.ssl.keyStorePassword", KEYSTORE_PASSWORD);
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
(hostname, sslSession) -> {
if (hostname.equals("localhost")) {
return true;
}
return false;
});
}
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}