1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
package beans;
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.ldap.*;
import javax.naming.directory.*;
import java.io.*;
public class Setpass {
public static void main (String[] args)
{
Hashtable env = new Hashtable();
String adminName = "admin";
String adminPassword = "pass";
String userName = "CN=Username Surname";
String oldPassword = "passwrod";
String newPassword = "password";
String searchBase = "DC=xxxxxxx,DC=net";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
//set security credentials, note using simple cleartext authentication
env.put(Context.SECURITY_PRINCIPAL,adminName);
env.put(Context.SECURITY_CREDENTIALS,adminPassword);
env.put(Context.SECURITY_AUTHENTICATION,"DIGEST-MD5"); //No other SALS worked with me
//connect to my domain controller
String ldapURL = "LDAP://xx.xxxxxxx.net:389";
env.put(Context.PROVIDER_URL,ldapURL);
try {
// Create the initial directory context
DirContext ctx = new InitialDirContext(env);
//set password is a ldap modfy operation
ModificationItem[] mods = new ModificationItem[2];
//Replace the "unicdodePwd" attribute with a new value
//Password must be both Unicode and a quoted string
String oldQuotedPassword = "\"" + oldPassword + "\"";
byte[] oldUnicodePassword = oldQuotedPassword.getBytes("UTF-16LE");
String newQuotedPassword = "\"" + newPassword + "\"";
byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", oldUnicodePassword));
mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
// Perform the update
ctx.modifyAttributes(userName + searchBase, mods);
System.out.println(userName + " " + mods);
System.out.println("Reset Password for: " + userName);
ctx.close();
}
catch (NamingException e) {
System.out.println("Problem resetting password: " + e);
}
catch (UnsupportedEncodingException e) {
System.out.println("Problem encoding password: " + e);
}
} |
Partager