程序原本使用配置全局变量方式导入证书库(使用的是jdk下默认证书库cacerts)
String javaHome = System.getProperty("java.home");
String keystore = Paths.get(javaHome, "/lib/security/cacerts").toString();
System.setProperty("javax.net.ssl.trustStore", keystore);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
这种方式重新导入证书文件需要重启程序才能生效。
后来发现改用自定义信任库可以实时生效,如下代码
String javaHome = System.getProperty("java.home");
String keystorePath = Paths.get(javaHome, "/lib/security/cacerts").toString();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(keystorePath), "changeit".toCharArray());
trustManagerFactory.init(keystore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustManagers, null);
SSLContext.setDefault(sc);
附加证书文件重新导入证书库的命令:
//先移除已经导入的同名证书(首次导入则不需要)
keytool -delete -alias [证书别名] -keystore [证书库路径] -storepass [证书库密码]
//导入证书
keytool -importcert -noprompt -trustcacerts -alias [证书别名] -keystore [证书库路径] -storepass [证书库密码] -file [导入的证书路径]