用JAVA实现LDAP与TLS的连接

kmbjn2e3  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(176)

当我尝试连接启用了TLS的LDAP服务器时,它失败了,但有以下例外情况。我的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://xxx.xxx.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://xxx.xxx.xxx.xxx");
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");
cedebl8k

cedebl8k1#

我已通过以下步骤修复了此问题
Keytool -import -alias certificatekey -file my-ca.crt -keystore my-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);

相关问题