Monday, April 5, 2010

HEre some important code for active directory password

    Update Active Directory Password with Code

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
import java.util.*;
import java.security.*;

public class ADUpdatePwd

{

private DirContext ldapContext;

private String baseName = ",ou=People,dc=bhatiacorp,dc=com";

private String serverIP = "127.0.0.1";

public void updatePassword(String username, String password) {
try {
String quotedPassword = "\"" + password + "\"";
char unicodePwd[] = quotedPassword.toCharArray();
byte pwdArray[] = new byte[unicodePwd.length * 2];
for (int i = 0; i < unicodePwd.length; i++) {
pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
}

ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("UnicodePwd", pwdArray));
ldapContext.modifyAttributes("cn=" + username + baseName, mods);
} catch (Exception e) {
System.out.println("ADUpdatePwd :: Update Password Error :: " + e);

}
}

private void setContext(String ldaphost, String ldapport, String adminID, String adminpassword, boolean useSSL) {
String providerurl = ldaphost + ":" + ldapport;
if (ldapport == "") {
ldapport = "636";
}
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, providerurl);
if (useSSL == true) {
// if SSL is used - use can use ssl enabled ldaphost
// eg. "ldaps://localhost:636"
// else
// eg. "ldap://localhost:636"
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, adminID);
env.put(Context.SECURITY_CREDENTIALS, adminpassword);
ldapContext = new InitialDirContext(env);
} catch (Exception ex) {
ex.printStackTrace();
}
}


public ADUpdatePwd() {
try {
setContext("ldaps://serverIP", "636", "CN=Administrator"+baseName, "p@ssw0rd1~", true);
} catch (Exception e) {
System.out.println("ADUpdatePwd :: Error :: " + e);
e.printStackTrace();

}
}

public static void main(String[] args) {
try {
/*
* Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); the keystore that holds trusted root certificates
* System.setProperty("javax.net.ssl.trustStore", "c:\\myCaCerts.jks");
* System.setProperty("javax.net.debug","all");
*/

ADUpdatePwd c = new ADUpdatePwd();
c.updatePassword("Bhatiar", "p@ssw0rd3");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}