当我尝试连接ldap服务器并启用tls时,它失败并出现以下异常。 我的my-ca.crt文件有什么问题吗?
public class LdapTest {
public static void main (String[] args) throws Exception {
LdapTest test = new LdapTest();
test.tryit();
System.out.println("Test End.");
}
public void tryit() throws Exception {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://9.111.xxx.xxx");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.REFERRAL,"ignore");
env.put(Context.SECURITY_PROTOCOL,"ssl");
String keystore = "/Users/dummy/Downloads/my-ca.crt";
System.setProperty("javax.net.ssl.trustStore", keystore);
DirContext ctx = null;
try {
ctx = new InitialDirContext(env);
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = ctx.search("cn=Directory Manager", "objectClass=*", sc);
while (results.hasMore()) {
SearchResult searchResult = results.next();
System.out.println("----------" + searchResult.toString() + "---------");
}
} catch (javax.naming.AuthenticationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
// ignore
}
}
}
}
}
此外,我可以使用虚拟DummySSLSocketFactory连接到我的ldap服务器,如下所示
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://9.111.156.147");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.REFERRAL,"ignore");
env.put(Context.SECURITY_PROTOCOL,"ssl");
env.put("java.naming.ldap.factory.socket", "com.test.ldap.DummySSLSocketFactory");
答案 0 :(得分:0)
我已按照以下步骤解决了此问题
Keytool -import -alias certificatekey -file my-ca.crt -keystore 我的-ca.jks
在Java代码中使用'my-ca.jks'而不是'my-ca.crt',然后我就可以成功连接到我的ldap服务器。
String keystore = "/Users/dummy/Downloads/my-ca.jks";
System.setProperty("javax.net.ssl.trustStore", keystore);