title: Using installed java key store certificate to connect to ldap
body: <p>I think this question might be already answered some where but I am not able to find any solution so far. My issue was, I want to connect to LDAP and find a user from the ldap directory but the problem here is, it is a secure LDAP, so I have to authenticate with the ldap server that I am who I am by a certificate. So, I have installed that certificate using the following command </p>
  
  <pre><code>keytool -importcert -file D:\KSTLMRADD01.dev.chartercom.com.cer -keystore cacerts -alias KSTLMRADD01.dev.chartercom.com.cer
  </code></pre>
  
  <p>so by using <strong><em>system.setproperty</em></strong> I am setting the <strong><em>javax.net.ssl.truststore</em></strong> location and keystore password, since I have around 100 certificates in java keystore it was unable to use the appropriate certificate while making the connection, please see the below code and if there is any mistake or suggestions please let me know. Any help would be really great full.</p>
  
  <pre><code>public class TestLdap{
  public static void main(String[] args){
  System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_152\\jre\\lib\\security\\cacerts");
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
  
  
      try {
          // use the service user to authenticate
          Hashtable&lt;String, Object&gt; serviceEnv = new Hashtable&lt;String, Object&gt;();
          serviceEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          serviceEnv.put(Context.PROVIDER_URL, ldapUrl);
          serviceEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
          serviceEnv.put(Context.SECURITY_PROTOCOL, "ssl");
          serviceEnv.put(Context.SECURITY_PRINCIPAL, serviceUserDN);
          serviceEnv.put(Context.SECURITY_CREDENTIALS, serviceUserPassword);
          LdapContext ctx = new InitialLdapContext(environment, null);
          ctx.setRequestControls(null);
          DirContect context = new InitialDirContext(environment);NamingEnumeration&lt;?&gt; namingEnum = ctx.search("ou=service_accounts,dc=com", "(objectclass=user)", getSimpleSearchControls());
  while (namingEnum.hasMore ()) {
      SearchResult result = (SearchResult) namingEnum.next ();    
      Attributes attrs = result.getAttributes ();
      System.out.println(attrs.get("sn"));
  
  }
  namingEnum.close();
  ctx.close();
  }}
  </code></pre>
  
  <p>So I tried the DirContext and LdapContext but both are not working for me.</p>