#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    93
    Rep Power
    27

    Can JNDI use a programmatically created keystore?


    I am writing a small program to validate the existence of an LDAP service when given a protocol, host ip address, and port number. I am trying to use JNDI to do so, but I am finding that the certificate for the LDAP service needs to be utilized by my program or the SSL handshake will fail.

    I want this to be usable on any machine I run it on, so I cannot specify the location of a keystore file in the program. Instead, I need to generate a new keystore, get the certificate from the LDAP server, and use that keystore file to authenticate. I have written the code to open an SSL socket connection with the remote host, retrieve the cert, and load it into a programmatically created keystore, my only problem is that I can't seem to figure out how to get JNDI to use my keystore file.

    I've posted a snippet from my code below. Can anyone help me out? How can I use my keystore file to establish this connection?

    Code:
    try {
    	myKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    	myKeystore.load(null, null);
    	X509Certificate cert = RetrieveSslCert.getCert(protocol, host, port, "myKeyStorePassword", myKeystore);
    	String alias = host;
    	myKeystore.setCertificateEntry(alias, cert);
    } catch (KeyStoreException e) {
    	throw new NonfatalInstallException(e.getMessage());
    } catch (FileNotFoundException e) {
    	throw new NonfatalInstallException(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
    	throw new NonfatalInstallException(e.getMessage());
    } catch (CertificateException e) {
    	throw new NonfatalInstallException(e.getMessage());
    } catch (IOException e) {
    	throw new NonfatalInstallException(e.getMessage());
    }
    
    
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, protocol + "://" + host + ":" + port);
    
    //utilize keystore file here???
    
    try {
    	DirContext ctx = new InitialDirContext(env);
    	if (ctx != null)
    		connectionValid = true;
    } catch (NamingException e) {
    	connectionValid = false;
    }
    Last edited by jasondj; October 5th, 2012 at 09:20 AM.

IMN logo majestic logo threadwatch logo seochat tools logo