在Undertow中启用HTTPS

时间:2015-01-12 16:37:35

标签: java ssl https keystore undertow

我们有一个有效的Apache mod_ssl配置。我想为Undertow启用HTTPS支持,以便它同时监听http和https,从而避免了对Apache的需求。

我已经看过Undertow的javadocs。 Undertow.Builder类有两个带有以下签名的addHttpsListener方法:

   public Builder addHttpsListener(int port, String host, 
       KeyManager[] keyManagers, TrustManager[] trustManagers);
   public Builder addHttpsListener(int port, String host,
       SSLContext sslContext) {

所以看起来我可以在使用Builder API引导Undertow时使用这些,例如

Undertow server = Undertow.builder()
                    .addHttpsListener(8443, "localhost", sslContext)
                    .build();

我不确定如何创建SSLContext变量,或者如何配置KeyManagers和TrustManagers。  拥有mod_ssl使用的证书文件,如何继续为Undertow启用HTTPS?

更新

根据hwellmann的回答,我重复使用SslContextFactory.createSslContext()方法。在此之前,我必须将我的公钥/私钥对转换为PKCS12格式并将其导入Java密钥库。

在下面提供SSL转换转换/导入命令(取自herehere),希望这对任何人都有用:

# Convert to PKCS12    
$ openssl pkcs12 -export -out output_cert.pfx -inkey input_cert.key -in input_cert.crt -certfile intermediate.crt

# Import into Java keystore
$ keytool -v -importkeystore -srckeystore output_cert.pfx -srcstoretype PKCS12 -destkeystore output_store.jks -deststoretype JKS

2 个答案:

答案 0 :(得分:5)

这不是特定于Undertow的,只是从带有证书的密钥库构建SSL上下文的问题。

有关与Undertow一起使用的示例,请参阅SslContextFactory.java

答案 1 :(得分:0)

Undertow源代码中有一个关于如何创建SslContext的示例: https://github.com/undertow-io/undertow/blob/e8473ec35c420b782e072723d1e6338548def842/examples/src/main/java/io/undertow/examples/http2/Http2Server.java#L76

SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore"));

...

private static SSLContext createSSLContext(final KeyStore keyStore, final KeyStore trustStore) throws Exception {
    KeyManager[] keyManagers;
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password("key"));
    keyManagers = keyManagerFactory.getKeyManagers();

    TrustManager[] trustManagers;
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);

    return sslContext;
}

...

private static KeyStore loadKeyStore(String storeLoc, String storePw) throws Exception {
    InputStream stream = Files.newInputStream(Paths.get(storeLoc));
    if(stream == null) {
        throw new IllegalArgumentException("Could not load keystore");
    }
    try(InputStream is = stream) {
        KeyStore loadedKeystore = KeyStore.getInstance("JKS");
        loadedKeystore.load(is, storePw.toCharArray());
        return loadedKeystore;
    }
}