Search code examples
javasslkeystoretomcat9

Java | Apache Tomcat 9 | Read keystore from memory


Is there a way in Apache Tomcat 9 (Java) to read a keystore for SSL encryption from a variable, meaning without the detour of saving the keystore to a file and then specifying the file path as property?

At the moment I pass the keystore into Apache like the following code:

Connector connector = new Connector();
connector.setScheme("https");
connector.setProperty("keyAlias", "alias-test");
connector.setProperty("keystorePass", "testpwd");
connector.setProperty("keystoreType", "PKCS12");
connector.setProperty("keystoreFile", "keystore.pfx");

Solution

  • To use an already configured KeyStore you need to use the appropriate setter methods, which since Tomcat 8.5 are:

    This sums up to something like this:

           final KeyStore trustStore = ...
           final KeyStore keyStore = ...
           // Certificate
           final SSLHostConfigCertificate certificate = new SSLHostConfigCertificate();
           certificate.setCertificateKeystore(keyStore);
           certificate.setCertificateKeyAlias("mykey");
           certificate.setCertificateKeyPassword("secret");
           // Host SSL configuration
           final SSLHostConfig sslHostConfig = new SSLHostConfig();
           sslHostConfig.setTrustStore(trustStore);
           sslHostConfig.addCertificate(certificate);
           // Connector
           final Connector connector = new Connector();
           connector.setScheme("https");
           connector.setSecure(true);
           connector.addSslHostConfig(sslHostConfig);
           connector.setProperty("SSLEnabled", "true");