SpringBoot服务间使用自签名证书实现https双向认证
阅读原文时间:2021年12月11日阅读:5

SpringBoot服务间使用自签名证书实现https双向认证

需要生成server-one和server-two的客户端密钥和一个信任库密钥

1.生成TrustStore(信任库)
  keytool -genkey -alias trustkeys -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore trustKeys.p12 -validity 36500

2.生成server-one客户端密钥
  keytool -genkey -alias server-one -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore server-one.p12 -validity 36500

3.生成server-two客户端密钥
  keytool -genkey -alias server-two -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore server-two.p12 -validity 36500

4.导出客户端公钥添加到信任库
 4.1 导出server-one的公钥
     keytool -keystore server-one.p12 -export -alias server-one -file server-one-publicKey.cer
 4.2 导出server-two的公钥
     keytool -keystore server-two.p12 -export -alias server-two -file server-two-publicKey.cer

5.添加客户端公钥到信任库
  keytool -import -alias server-one -v -file server-one-publicKey.cer -keystore trustKeys.p12
  keytool -import -alias server-two -v -file server-two-publicKey.cer -keystore trustKeys.p12

以上2、3、4和5步骤填写信息与1基本相同,不再重复截图展示

部分命令解释

genkey 表示要创建一个新的密钥。
alias 表示 keystore 的别名。
keyalg 表示使用的加密算法是 RSA ,一种非对称加密算法。
keysize 表示密钥的长度。
keystore 表示生成的密钥存放位置。
validity 表示密钥的有效时间,单位为天。

1、拷贝相应密钥到resources

2、客户端配置文件application.properties对应的配置项

# 开启ssl
server.ssl.enabled=true
server.ssl.client-auth=need
#server.ssl.protocol=TLS
server.ssl.key-store=classpath:ssl/server-one.p12
#server.ssl.key-password=123456
server.ssl.key-store-password=123456
server.ssl.key-store-type=PKCS12
server.ssl.keyAlias=server-one

server.ssl.trust-store=classpath:ice-ca/trustKeys.p12
server.ssl.trust-store-password=123456
server.ssl.trust-store-type=PKCS12

3、服务端配置文件application.properties对应的配置项

# 开启ssl
server.ssl.enabled=true
server.ssl.client-auth=need
#server.ssl.protocol=TLS
server.ssl.key-store=classpath:ssl/server-two.p12
#server.ssl.key-password=123456
server.ssl.key-store-password=123456
server.ssl.key-store-type=PKCS12
server.ssl.keyAlias=server-two

server.ssl.trust-store=classpath:ice-ca/trustKeys.p12
server.ssl.trust-store-password=123456
server.ssl.trust-store-type=PKCS12

4、pom.xml配置文件添加配置项如下

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
            <include>ssl/server-one.p12</include>
            <include>ice-ca/trustKeys.p12</include>
        </includes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>

5、启动服务并验证https

浏览器访问:https://localhost:8970/platformdictionary/queryDeviceType

此时无法访问

单击server-one.p12或server-two.p12为浏览器安装证书

安装后再次访问

点击确定后即可访问到页面

6、配置RestTemplate

pom添加httpclient支持

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

设置RestTemplate支持https请求

package com.hollysys.smartfactory.icedata.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.time.Duration;

/**
 * Created by chendy on 2021/12/18 15:47
 */
@Configuration
@Slf4j
public class RestTemplateConfig {
    @Value("${server.ssl.key-store-type}")
    String clientKeyType;
    @Value("${server.ssl.key-store}")
    String clientPath;
    @Value("${server.ssl.key-store-password}")
    String clientPass;
    @Value("${server.ssl.trust-store-type}")
    String trustKeyType;
    @Value("${server.ssl.trust-store}")
    String trustPath;
    @Value("${server.ssl.trust-store-password}")
    String trustPass;

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = null;
        try {
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            // 客户端证书类型
            KeyStore clientStore = KeyStore.getInstance(clientKeyType);
            // 加载客户端证书,即自己的私钥
            InputStream keyStream = getClass().getClassLoader().getResourceAsStream(clientPath);
            clientStore.load(keyStream, clientPass.toCharArray());
            // 创建密钥管理工厂实例
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            // 初始化客户端密钥库
            keyManagerFactory.init(clientStore, clientPass.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            // 创建信任库管理工厂实例
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore trustStore = KeyStore.getInstance(trustKeyType);
            InputStream trustStream = getClass().getClassLoader().getResourceAsStream(trustPath);
            trustStore.load(trustStream, trustPass.toCharArray());

            // 初始化信任库
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            // 建立TLS连接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            // 初始化SSLContext
            sslContext.init(keyManagers, trustManagers, new SecureRandom());
            // INSTANCE 忽略域名检查
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients
                    .custom()
                    .setSSLSocketFactory(sslConnectionSocketFactory)
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();
            requestFactory.setHttpClient(httpclient);
            requestFactory.setConnectTimeout((int) Duration.ofSeconds(15).toMillis());
            restTemplate = new RestTemplate(requestFactory);
        } catch (KeyManagementException | FileNotFoundException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException e) {
            e.printStackTrace();
        }
        return restTemplate;
    }
}

7、添加测试代码

server-one中的test添加代码

@Test
public void testHello(){
    String url = "https://127.0.0.1:8970/platformdictionary/queryDeviceType";
    ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
    System.out.println(forEntity.toString());
}

server-two中的controller添加代码

@RestController
public class ServerTwoController {

    @RequestMapping("/get")
    public String get() {
        return "双向认证成功";
    }
}

测试执行结果

<200,双向认证成功,[Content-Type:"text/plain;charset=UTF-8", Content-Length:"3", Date:"Fri, 21 May 2021 08:12:51 GMT", Keep-Alive:"timeout=60", Connection:"keep-alive"]>