如何在Spring Boot和Tomcat中以编程方式提供密钥库文件?

huangapple go评论82阅读模式
英文:

How can I programmatically supply the keystore file with Spring Boot and Tomcat?

问题

由于安全考虑,我们希望摆脱磁盘上的P12文件,并直接从云提供商的保险库中获取它。

既然可以配置密钥库的密码,我可以使用https://stackoverflow.com/a/44971126/4460877来设置它。

是否有一种类似的方法来配置密钥库文件,而不是从云提供商获取文件位置?

英文:

I know that we can configure the keystore's file location using

server.ssl.key-store=file:/path/to/file.p12

Due to security concerns, we would like to get rid of the P12 file on disk and fetch it directly from the cloud providers vault.
Since the keystore's password can be configured, I can set it using https://stackoverflow.com/a/44971126/4460877

Is there a similar approach for configuring the keystore file rather than the file location by fetching it from the cloud provider?

答案1

得分: 2

我能够使用WebServerFactoryCustomizer以编程方式设置密钥库文件,如下所示:

@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatSslStoreCustomizer() {
    // 提供密钥库密码
    String keyStorePassword;
    // 以流的形式提供密钥库文件
    InputStream keyStoreFile;
    KeyStore keyStore;

    try (InputStream is = keyStoreFile) {
        keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
        keyStore.load(is, keyStorePassword.toCharArray());
    } catch (Exception e) {
        throw new RuntimeException("无法加载密钥库文件;原因:" + e.getMessage(), e);
    }

    return tomcat -> tomcat.setSslStoreProvider(new SslStoreProvider() {
        @Override
        public KeyStore getKeyStore() {
            return keyStore;
        }

        @Override
        public KeyStore getTrustStore() {
            return null;
        }
    });
}

请注意,这是Java代码,用于以编程方式设置密钥库文件。

英文:

I was able to set the keystore file programmatically using the WebServerFactoryCustomizer as follows

    @Bean
    public WebServerFactoryCustomizer&lt;TomcatServletWebServerFactory&gt; tomcatSslStoreCustomizer() {
        // Supply key store password
        String keyStorePassword;
        // Supply key store file as a stream
        InputStream keyStoreFile;
        KeyStore keyStore;

        try (InputStream is = keyStoreFile) {
            keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
            keyStore.load(is, keyStorePassword.toCharArray());
        }
        catch (Exception e) {
            throw new RuntimeException(&quot;Cannot load keystore file; cause: &quot; + e.getMessage(), e);
        }

        return tomcat -&gt; tomcat.setSslStoreProvider(new SslStoreProvider() {
            @Override
            public KeyStore getKeyStore() {
                return keyStore;
            }

            @Override
            public KeyStore getTrustStore() {
                return null;
            }
        });
    }

huangapple
  • 本文由 发表于 2020年8月5日 08:56:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63256949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定