Spring Boot读取trustStore出错

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小结

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值