java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot https双向认证

springboot基于keytool实现https的双向认证示例教程

作者:佐氵谙

这篇文章主要介绍了springboot基于keytool实现https的双向认证,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、环境准备

服务器信息如下:

操作系统说明
server-one服务器1
server-two服务器2

二、keytool命令解释

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

-keypass 私钥访问密码:123456

-storepass keystone文件访问密码:123456

删除导入的信任证书

keytool -delete -alias 删除证书的别名 -keystore 信任库
keytool -delete -alias server-one -keystore /home/keytool/trustKeys.p12

三、服务器server-one生成密钥 服务器

1生成TrustStore(信任库.P12)

keytool -genkey -alias trustkeys -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore /home/keytool/trustKeys.p12 -validity 36500

服务器1生成客户端密钥(.P12)

keytool -genkey -alias server-one -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore /home/keytool/server-one.p12 -validity 36500

服务器1导出客户端公钥(.cer)

keytool -keystore /home/keytool/server-one.p12 -export -alias server-one -file /home/keytool/server-one-publicKey.cer

添加客户端(服务器2)公钥到服务器1的信任库(双向认证需要操作此步骤)

keytool -import -alias server-two -v -file /home/keytool/server-two-publicKey.cer -keystore /home/keytool/trustKeys.p12

从服务器1生成客户端密钥(.P12)文件中导出私钥文件(.key)

openssl pkcs12 -in /home/keytool/server-one.p12  -nodes -nocerts -out /home/keytool/server-one.key

从服务器1导出的客户端公钥(.cer)文件中导出公钥文件(.pem)

openssl x509 -inform der -in /home/keytool/server-one-publicKey.cer -out /home/keytool/server-one.pem

四、服务器server-two生成密钥(参考服务器1)

服务器2生成TrustStore(信任库.P12)

keytool -genkey -alias trustkeys -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore /home/keytool/trustKeys.p12 -validity 36500

服务器2生成客户端密钥(.P12)

keytool -genkey -alias server-two -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore /home/keytool/server-two.p12 -validity 36500

服务器2导出客户端公钥(.cer)

keytool -keystore /home/keytool/server-two.p12 -export -alias server-one -file /home/keytool/server-two-publicKey.cer

添加客户端(服务器1)的公钥到服务器2的信任库(双向认证需要操作此步骤)

keytool -import -alias server-one -v -file /home/keytool/server-one-publicKey.cer -keystore /home/keytool/trustKeys.p12

从服务器2生成客户端密钥(.P12)文件中导出私钥文件(.key)

openssl pkcs12 -in /home/keytool/server-two.p12  -nodes -nocerts -out /home/keytool/server-two.key

从服务器2导出的客户端公钥(.cer)文件中导出公钥文件(.pem)

openssl x509 -inform der -in /home/keytool/server-two-publicKey.cer -out /home/keytool/server-two.pem

 五、配置SpringBoot支持https

1、服务器1配置文件application.properties

#开启ssl
server.ssl.enabled=true
#配置的值 need双向验证 none不验证客户端 want会验证,但不强制验证,即验证失败也可以成功建立连接
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

2、服务器2配置文件application.properties

#开启ssl
server.ssl.enabled=true
#配置的值 need双向验证 none不验证客户端 want会验证,但不强制验证,即验证失败也可以成功建立连接
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

3、拷贝相应密钥到resources目录下

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>

六、配置RestTemplate工具类

1、pom添加httpclient支持

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

2、设置RestTemplate支持https请求

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;
/**
 * HTTPS通信双向认证工具类
 *
 * @author xiwh
 */
@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);
            // 创建httpClient对象
            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;
    }
}

3、测试代码

服务器1(server-one)请求接口代码

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

服务器2(server-two)controller代码

    /**
     * https测试方法
     *
     * @return
     */
    @ApiOperation("https测试方法")
    @GetMapping("/httpsTest")
    public Result httpsTest() {
        log.info("服务器server-two响应成功!");
        return Result.SUCCESS();
    }

服务器2(server-two)执行结果

<200,{"code":1,"success":true,"msg":"操作成功","data":null}>

七、Nginx配置ssl证书

 
    server  {
    #监听前端访问端口
    listen       9028 ssl;
    #服务器地址
    server_name  47.104.239.238;
    charset utf-8;
    client_max_body_size 20M;
    #双向认证 开启校验客户端
    #ssl_verify_client on;
    #server公钥 或 阿里云证书 一般是crt文件
    ssl_certificate         /home/keytool/server.pem;
    #server私钥 或 阿里云证书 一般是key文件
    ssl_certificate_key     /home/keytool/server.key;
    #双向认证 客户端公钥
    #ssl_client_certificate  /home/keytool/server.pem;
    #支持ssl协议版本
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    #配置服务器可使用的加密算法
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    # 指定服务器密码算法在优先于客户端密码算法时,使用 SSLv3 和 TLS 协议
    ssl_prefer_server_ciphers on;
    ssl_session_timeout 5m;
    #前端请求后端接口
    location  /prod-api/ {
    proxy_pass https://47.104.239.238:8077/;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Nginx-Proxt true;
    proxy_set_header HTTP_X_FORWORDED_FOR $remote_addr;
    proxy_ssl_certificate     /home/keytool/server.pem;
    proxy_ssl_certificate_key /home/keytool/server.key;
    proxy_ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 SSLv2 SSLv3 ;
    proxy_ssl_ciphers         ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    proxy_ssl_session_reuse  off;
    proxy_ssl_server_name on;
    proxy_redirect off;
  }
    #前端包目录
    location / {
    root   /mnt/project/sinotmemc/dist;
    try_files $uri $uri/ /index.html;
    index  index.html index.htm;
  }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    root   html;
  }
  }

参考资料:

spring boot 使用RestTemplate通过证书认证访问https实现SSL请求

到此这篇关于springboot基于keytool实现https的双向认证的文章就介绍到这了,更多相关springboot https双向认证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文