我需要支持多个LDAP服务器。有些人可能会使用SSL。我可以下载证书并将其添加到Java信任库文件中。添加证书后,如果我立即尝试使用SSL登录,则登录失败。如果我重新启动JVM,登录工作正常。
这是正常行为吗?是否可以在不重新启动JVM的情况下进行登录?
答案 0 :(得分:0)
创建自定义SSLContext,然后创建SSLContext.getSocketFactory()。
public static SSLContext createSSLContext(Certificate ca, PrivateKey key, Certificate[] chain)
KeyStore keyStore = KeyStore.getInstance("JCEKS");
char[] pwd = new char[1];
keyStore.load(null, pwd);
if (key != null && chain != null) {
keyStore.setKeyEntry("key", key, pwd, chain);
}
if (ca != null) {
keyStore.setCertificateEntry("cert", ca);
}
SSLContext sc = SSLContext.getInstance("SSL");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, pwd);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sc.init(key != null ? keyManagerFactory.getKeyManagers() : null,
ca != null ? trustManagerFactory.getTrustManagers() : null,
null);
return sc;
}