小结
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

文章讲述了在SpringBoot应用中遇到读取trustStore文件时出现的错误,包括IllegalStateException和NoSuchAlgorithmException等。问题的根本原因是程序错误地将默认的cacerts文件用作信任存储,而不是预期的test.store。通过使用ClassPathResource加载文件,获取绝对路径,并设置系统属性来指定正确的trustStore和密码,成功解决了问题。
959

被折叠的 条评论
为什么被折叠?



