in Spring

Spring Boot读取trustStore出错

小结

Spring Boot读取trustStore报错,进行了排查并解决。

问题

读取公钥证书并添加到trustStore中,trustStore名称是test.store,这里在Spring Boot中使用程序访问,报以下错:

...
Caused by: java.lang.IllegalStateException: could not create the default ssl context
...
Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
...
Caused by: java.security.KeyStoreException: problem accessing trust store
...
Caused by: java.io.IOException: Keystore was tampered with, or password was incorrect
...
Caused by: java.security.UnrecoverableKeyException: Password verification failed
...

解决

首先想到的是密码设置有误,使用以下指令进行排查,密码没问题,可以正常读取:

keytool -list -v -keystore test.store
Enter keystore password:666666
...
...

经过跟踪调试,发现是trustStore文件test.store没有被正确读取。读取到的文件是:C:\Program Files\Java\jdk-11.0.16.1\lib\security\cacerts并被设置到 javax.net.ssl.trustStore。这里test.store这个文件是放在resource下的,修改后使用以下方法可以正常正确读取,问题解决。

        String storePath = null;
        File resource = null;
        try {
            resource = new ClassPathResource(
                    "test.store").getFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        storePath = resource.getAbsolutePath();

        System.setProperty("javax.net.ssl.trustStore",
                storePath);
        // 设置trustStore的读取密码
        System.setProperty("javax.net.ssl.trustStorePassword", "666666");

以上storePath的内容为: D:\Spring_Boot_Test\target\classes\test.store

参考

Stackoverflow: keytool error Keystore was tampered with, or password was incorrect
Access a File from the Classpath in a Spring Application

Write a Comment

Comment