java 如何加载位于资源文件夹(maven)内的密钥库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14990751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:07:06  来源:igfitidea点击:

How to load a keystore, which is inside the resource folder (maven)?

javamavenresourceskeystoretruststore

提问by David Sonnenfeld

I have a custom SSL factory, where I load my own truststore.

我有一个自定义 SSL 工厂,我可以在其中加载自己的信任库。

Now when I put the truststore.jks file into the project root folder, it works with the following line:

现在,当我将 truststore.jks 文件放入项目根文件夹时,它使用以下行:

ks.load(new FileInputStream("/truststore.jks", passphrase);

But I want my truststore inside my resource folder, which was built with maven where the path is src/main/resources.

但我希望我的信任库位于我的资源文件夹中,该文件夹是用 maven 构建的,路径是src/main/resources

Then I do and it doesn't work with the following line:

然后我做了,它不适用于以下行:

ks.load(this.getClass().getResourcesAsStream("/truststore.jks"), passphrase);

Though the input stream exists. I checked it. It only fails when I do ks.load(...).

虽然输入流存在。我查了一下。它仅在我执行 ks.load(...) 时失败。

The exception that I get is:

我得到的例外是:

 java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

Why is that?

这是为什么?

Regards, Dave

问候, 戴夫

采纳答案by David Sonnenfeld

Strange, it works now...

奇怪,现在可以用了……

I had

我有

Properties systemProps = System.getProperties();
systemProps.put( "javax.net.ssl.trustStore", "/truststore.jks");
systemProps.put( "javax.net.ssl.trustStorePassword", "changeit");
System.setProperties(systemProps);

and change the second line to

并将第二行更改为

systemProps.put( "javax.net.ssl.trustStore", "src/main/resources/truststore.jks");

Anyone knows why? Is this solution ok?

有谁知道为什么?这个解决方案好吗?