我尝试使用带有RestTemplate的密钥和证书来调用双向SSL安全系统。我使用密钥库来配置证书和密钥。这是生成密钥库的步骤。


openssl pkcs12 -export -in cert.pem -inkey "privateKey.pem" -certfile cert.pem -out myProject_keyAndCertBundle.p12
keytool -importkeystore -srckeystore myProject_keyAndCertBundle.p12 -srcstoretype PKCS12 -destkeystore keystore.jks.jks


然后,我在主类上对其进行了配置,如下所示。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);


        System.setProperty("javax.net.ssl.keyStore", "keystore.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "password");
        System.setProperty("javax.net.ssl.keyStoreType", "JKS");
    }

}


它可以成功工作。

我的问题是,是否有任何方法可以在application.yml中设置此密钥存储区

我尝试如下。但是在那种情况下,我还需要一个证书才能与我的spring boot应用程序连接。

server:
  port: 8443
  ssl:
    key-store: classpath:keystore.jks
    key-store-password: password
security:
  headers:
    hsts: NONE

最佳答案

您在application.yml中所做的是保护springboot应用程序。您正在使用提供给您的私钥来保护springboot应用程序,这是错误的。

您需要的是能够在进行外部服务调用之前动态加载给您的密钥库的能力,如下所示:

// Key Store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientKeyStore, clientKeyStorePwd);

// Trust Store
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(serverTrustStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());


KeyStore部分是提供给您的密钥库,其中包含私钥和证书链。而且TrustStore仅包含签署私钥的CA链。

关于java - yml中的KeyStore配置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53874341/

10-10 11:53