LDAP的java操作方法

package com.bond520.ldap;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;


import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;


import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;


public class LadpControl {


static byte[] bslt = new byte[0];


private DirContext ctx = null;


/*
dn: uid=mdx,ou=people,dc=yj,dc=com
objectClass: person
objectClass: inetOrgPerson
cn: Super Special
displayName: Super Special
givenName: Super
mail: [email protected]
sn: mdx
uid: mdx
userPassword:: eWo=
 
*/
public static void main(String[] args) {
LadpControl ldap = new LadpControl();
try {
ldap.init();


//下面插入记录
ldap.addUser(ldap.ctx,"cn=aibaoling,ou=staff,ou=bond,dc=bond520,dc=com") ;


//检查用户是否存在
//System.out.println( ldap.checkUser(ldap.ctx,"cn=aibaoling" , "renyong" , "ou=staff,ou=bond,dc=bond520,dc=com") ) ;
//修改密码
//ldap.modifyPassword(ldap.ctx,"uid=mdy,ou=people,dc=yj,dc=com" , "yj")  ;
//删除帐号
//ldap.delUser(ldap.ctx,"cn=aibaoling,ou=staff,ou=bond,dc=bond520,dc=com") ;
//修改信息
//ldap.modifyUser(ldap.ctx,"cn=aibaoling,ou=staff,ou=bond,dc=bond520,dc=com") ;
//查询某个用户
//ldap.ShowUsers(ldap.ctx,"cn=aibaoling" , "ou=staff,ou=bond,dc=bond520,dc=com") ;
//查询符合条件用户
//ShowUsers(ctx,"uid=md*" , "ou=people,dc=yj,dc=com") ;
//查询包含子结点数据
//ShowUsers(ctx,"cn=*" , "dc=yj,dc=com") ;
//浏览某个用户
//ldap.showProperties(ldap.ctx,"cn=renyong,ou=staff,ou=bond,dc=bond520,dc=com") ;
//浏览某个用户的某些属性
//ldap.showProperties(ldap.ctx,"cn=renyong,ou=staff,ou=bond,dc=bond520,dc=com",new String[]{"cn","objectClass"}) ;


} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("认证失败");
} catch (Exception e) {
System.out.println("认证出错:");
e.printStackTrace();
} finally {
if (ldap.ctx != null)
try {
ldap.ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}


}


public void init() throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://10.0.0.8/");


env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=username,dc=bond520,dc=com");
env.put(Context.SECURITY_CREDENTIALS, "password");
ctx = new InitialDirContext(env);
System.out.println("认证成功");
}


public boolean verify(String ldappw, String inputpw)
throws NoSuchAlgorithmException {
MessageDigest md = null;
int len = 0;


// 取出加密字符
if (ldappw.startsWith("{SSHA}")) {
ldappw = ldappw.substring(6);
md = MessageDigest.getInstance("SHA-1");
len = 20;
} else if (ldappw.startsWith("{SHA}")) {
ldappw = ldappw.substring(5);
md = MessageDigest.getInstance("SHA-1");
len = 20;
} else if (ldappw.startsWith("{MD5}")) {
ldappw = ldappw.substring(5);
md = MessageDigest.getInstance("MD5");
len = 16;
} else if (ldappw.startsWith("{SMD5}")) {
ldappw = ldappw.substring(6);
md = MessageDigest.getInstance("MD5");
len = 16;
}


// 解码BASE64
byte[] ldappwbyte = Base64.decode(ldappw);
byte[] shacode;
byte[] salt;


// 前20位是SHA-1加密段,20位后是最初加密时的随机明文
if (ldappwbyte.length <= len) {
shacode = ldappwbyte;
salt = new byte[0];
} else {
shacode = new byte[len];
salt = new byte[ldappwbyte.length - len];
System.arraycopy(ldappwbyte, 0, shacode, 0, len);
System.arraycopy(ldappwbyte, len, salt, 0, salt.length);
}


// 把用户输入的密码添加到摘要计算信息
md.update(inputpw.getBytes());
// 把随机明文添加到摘要计算信息
md.update(salt);


// 按SSHA把当前用户密码进行计算
byte[] inputpwbyte = md.digest();


// 返回校验结果
return MessageDigest.isEqual(shacode, inputpwbyte);
}


public String encry(String method, String pass, byte[] salt)
throws NoSuchAlgorithmException {
MessageDigest md = null;


// 取出加密字符
if (method.equals("{SSHA}")) {
md = MessageDigest.getInstance("SHA-1");
} else if (method.equals("{SHA}")) {
md = MessageDigest.getInstance("SHA-1");
} else if (method.equals("{MD5}")) {
md = MessageDigest.getInstance("MD5");
} else if (method.equals("{SMD5}")) {
md = MessageDigest.getInstance("MD5");
}


// 前20位是SHA-1加密段,20位后是最初加密时的随机明文
if (salt == null) {
salt = new byte[0];
}


// 把用户输入的密码添加到摘要计算信息
md.update(pass.getBytes());
// 把随机明文添加到摘要计算信息
md.update(salt);


// 按SSHA把当前用户密码进行计算
byte[] inputpwbyte = md.digest();
byte[] new_bytes = inputpwbyte;


if (salt.length > 0) {
new_bytes = new byte[inputpwbyte.length + salt.length];
System.arraycopy(inputpwbyte, 0, new_bytes, 0, inputpwbyte.length);
System.arraycopy(salt, 0, new_bytes, inputpwbyte.length,
salt.length);
}


// 返回校验结果
return method + Base64.encode(new_bytes);
}
//cn=aibaoling,ou=staff,ou=bond,dc=bond520,dc=com
public void addUser(DirContext context, String dn)
throws NamingException, NoSuchAlgorithmException {
Attributes attrs = new BasicAttributes();
attrs.put("sn", "na");
attrs.put("displayName", "艾宝林");
attrs.put("employeeNumber", "418");
attrs.put("uid", "aibaoling");
String x = encry("{SHA}", "123456", bslt);
attrs.put("userPassword", x);
System.out.println(x);
//我们需要加密存储,否则大家都看到了


//the following attribute has two values  
Attribute objclass = new BasicAttribute("objectClass");
objclass.add("inetOrgPerson");
objclass.add("top");
attrs.put(objclass);


//下面两种方法都可以
//context.bind(dn, null, attrs);  
context.createSubcontext(dn, attrs);
}


public boolean checkUser(DirContext context, String dn, String password,
String parent) throws NamingException, NoSuchAlgorithmException {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration en = context.search(parent, dn,
constraints); // 查询所有用户
boolean success = false;


while (en != null && en.hasMoreElements()) {
SearchResult result = en.nextElement();
System.out.println("dn: " + result.getNameInNamespace());


Attributes attrs = result.getAttributes();
if (attrs == null) {
System.out.println("No   attributes");
} else {
Attribute attr = attrs.get("userPassword");
Object o = attr.get();
byte[] s = (byte[]) o;
String pwd2 = new String(s);
success = verify(pwd2, password);
}
}
return success;
}


public void ShowUsers(DirContext context, String dn, String parent)
throws NamingException, NoSuchAlgorithmException {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration en = context.search(parent, dn,
constraints); // 查询所有用户


while (en != null && en.hasMoreElements()) {
SearchResult result = en.nextElement();
//System.out.println("dn: " + result.getName() + "," + parent);
System.out.println("dn: " + result.getNameInNamespace());


Attributes attrs = result.getAttributes();
if (attrs != null) {
NamingEnumeration atte = (NamingEnumeration) attrs
.getAll();
while (atte.hasMore()) {
Attribute attr = atte.next();
int size = attr.size();
if (size == 1) {
Object obj = attr.get();
if (obj instanceof byte[]) {
System.out.println(attr.getID() + ":: "
+ Base64.encode((byte[]) obj));
} else {
System.out.println(attr.getID() + ": " + obj);
}
} else {
for (int i = 0; i < size; i++) {
Object obj = attr.get(i);
if (obj instanceof byte[]) {
System.out.println(attr.getID() + ":: "
+ Base64.encode((byte[]) obj));
} else {
System.out.println(attr.getID() + ": " + obj);
}
}
}
}
}
}
}


//显示某个结点属性
public void showProperties(DirContext context, String dn)
throws NamingException, NoSuchAlgorithmException {
Attributes attrs = context.getAttributes(dn);


System.out.println("dn: " + dn);


if (attrs != null) {
NamingEnumeration atte = (NamingEnumeration) attrs
.getAll();
while (atte.hasMore()) {
Attribute attr = atte.next();
int size = attr.size();
if (size == 1) {
Object obj = attr.get();
if (obj instanceof byte[]) {
System.out.println(attr.getID() + ":: "
+ Base64.encode((byte[]) obj));
} else {
System.out.println(attr.getID() + ": " + obj);
}
} else {
for (int i = 0; i < size; i++) {
Object obj = attr.get(i);
if (obj instanceof byte[]) {
System.out.println(attr.getID() + ":: "
+ Base64.encode((byte[]) obj));
} else {
System.out.println(attr.getID() + ": " + obj);
}
}
}
}
}
}


//显示某个结点某些属性
public void showProperties(DirContext context, String dn,
String[] properties) throws NamingException,
NoSuchAlgorithmException {
Attributes attrs = context.getAttributes(dn, properties);


System.out.println("dn: " + dn);


if (attrs != null) {
NamingEnumeration atte = (NamingEnumeration) attrs
.getAll();
while (atte.hasMore()) {
Attribute attr = atte.next();
int size = attr.size();
if (size == 1) {
Object obj = attr.get();
if (obj instanceof byte[]) {
System.out.println(attr.getID() + ":: "
+ Base64.encode((byte[]) obj));
} else {
System.out.println(attr.getID() + ": " + obj);
}
} else {
for (int i = 0; i < size; i++) {
Object obj = attr.get(i);
if (obj instanceof byte[]) {
System.out.println(attr.getID() + ":: "
+ Base64.encode((byte[]) obj));
} else {
System.out.println(attr.getID() + ": " + obj);
}
}
}
}
}
}


public void modifyPassword(DirContext context, String dn, String password)
throws NamingException, NoSuchAlgorithmException {
ModificationItem[] modificationItem = new ModificationItem[1];
modificationItem[0] = new ModificationItem(
DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
"userPassword", encry("{SHA}", password, bslt)));
context.modifyAttributes(dn, modificationItem);
}


public void modifyUser(DirContext context, String dn)
throws NamingException, NoSuchAlgorithmException {
ModificationItem[] modificationItem = new ModificationItem[1];


//ADD_ATTRIBUTE
//REPLACE_ATTRIBUTE
//REMOVE_ATTRIBUTE
modificationItem[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("displayName","top"));


context.modifyAttributes(dn, modificationItem);
}


public void delUser(DirContext context, String dn) throws NamingException {
context.destroySubcontext(dn);
}
}

你可能感兴趣的:(java)