在嵌入式Apache Tomcat 9中启用SSL并以编程方式添加证书

时间:2019-06-20 07:34:24

标签: java ssl tomcat

我有以下代码来启动软件:

public static void main(String[] args) throws Exception {
    // set system property for exit on failure
    System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true");

    // create tomcat
    Tomcat tomcat = new Tomcat();

    // create connector, configure and add to tomcat
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setMaxPostSize(-1);
    connector.setPort(8080);
    connector.setURIEncoding("UTF-8");
    ((Http11NioProtocol)connector.getProtocolHandler()).setConnectionUploadTimeout(36000000);
    ((Http11NioProtocol)connector.getProtocolHandler()).setDisableUploadTimeout(false);
    ((Http11NioProtocol)connector.getProtocolHandler()).setConnectionTimeout(3600000);
    ((Http11NioProtocol)connector.getProtocolHandler()).setCompression("on");
    ((Http11NioProtocol)connector.getProtocolHandler()).setCompressibleMimeType("text/html,text/xml,text/plain,application/javascript");
    tomcat.setConnector(connector);

    // add web app with jsps and servlets
    StandardContext standardContext = (StandardContext)tomcat.addWebapp("", new File(".").getAbsolutePath()+"/src/webroot");
    standardContext.getJarScanner().setJarScanFilter(new JarScanFilter() { @Override public boolean check(JarScanType jarScanType, String s) {
        if(s != null){
            if(s.startsWith("mchange-commons-java")){
                return false;
            }
        }

        return true;
    }});
    standardContext.setParentClassLoader(Run.class.getClassLoader());
    WebResourceRoot webResourceRoot = new StandardRoot(standardContext);
    File additionWebInfClassesFolder = new File(new File(".").getAbsolutePath(), "target/classes");
    WebResourceSet webResourceSet = new DirResourceSet(webResourceRoot, "/WEB-INF/classes", additionWebInfClassesFolder.getAbsolutePath(), "/");
    webResourceRoot.addPreResources(webResourceSet);
    standardContext.setResources(webResourceRoot);

    // start tomcat
    tomcat.start();

    // stay in this method as long as tomcat is running
    tomcat.getServer().await();
}

现在我有了我的证书文件(私钥,证书),并且想向此Tomcat服务器添加SSL功能。我知道这可能不是最佳做法,但我正在寻找一种非常简单的方法。我知道我可以创建一个密钥库文件并将属性添加到连接器,但是我基本上想要的是在证书内容中包含一个字符串并应用它。

1 个答案:

答案 0 :(得分:1)

我的解决方案看起来非常类似于我最终在这里偶然找到的可帮助我解决问题的代码:https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ServingLayer.java#L202

注意:我相信我正在使用Tomcat 10。

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);

    NightMode = AppCompatDelegate.getDefaultNightMode();

    sharedPreferences = getSharedPreferences("SharedPrefs", MODE_PRIVATE);
    editor = sharedPreferences.edit();

    editor.putInt("NightModeInt", NightMode);
    editor.apply();
}