import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;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.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class LdapUtil {
/**
* eg:onnectLDAP("192.168.1.242", "389", "ldap",
* "12345","dc=times,dc=home")
*/
public static DirContext connectLDAP(String ip, String port,
String root_user, String root_password, String root) {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://" + ip + ":" + port + "/" + root);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=" + root_user + "," + root + "");
env.put(Context.SECURITY_CREDENTIALS, root_password);
DirContext ctx = null;
try {
// 链接ldap
ctx = new InitialDirContext(env);
System.out.println("root认证成功");
return ctx;
} catch (javax.naming.AuthenticationException e) {
System.out.println("root认证失败");} catch (Exception e) {
System.out.println("root认证出错:");
e.printStackTrace();
}
return null;
}public static void closeCtx(DirContext ctx) {
try {
ctx.close();
} catch (NamingException ex) {
System.out.println("LDAP连接关闭失败");
}
}public static boolean verifySHA(String ldappw, String inputpw)
throws NoSuchAlgorithmException {
// MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1
MessageDigest md = MessageDigest.getInstance("SHA-1");// 取出加密字符
if (ldappw.startsWith("{SSHA}")) {
ldappw = ldappw.substring(6);
} else if (ldappw.startsWith("{SHA}")) {
ldappw = ldappw.substring(5);
} else {
return false;
}// 解码BASE64
byte[] ldappwbyte = Base64.decode(ldappw);
byte[] shacode;
byte[] salt;// 前20位是SHA-1加密段,20位后是最初加密时的随机明文
if (ldappwbyte.length <= 20) {
shacode = ldappwbyte;
salt = new byte[0];
} else {
shacode = new byte[20];
salt = new byte[ldappwbyte.length - 20];
System.arraycopy(ldappwbyte, 0, shacode, 0, 20);
System.arraycopy(ldappwbyte, 20, salt, 0, salt.length);
}// 把用户输入的密码添加到摘要计算信息
md.update(inputpw.getBytes());
// 把随机明文添加到摘要计算信息
md.update(salt);// 按SSHA把当前用户密码进行计算
byte[] inputpwbyte = md.digest();// 返回校验结果
return MessageDigest.isEqual(shacode, inputpwbyte);
}/**
*
* @param usr
* @param pwd
* @param ctx
* @return 1:密码不正确,-1:验证程序错误
* @throws NoSuchAlgorithmException
*/
public static String checkUser(String usr, String pwd, DirContext ctx)
throws NoSuchAlgorithmException {
if (ctx != null) {
try {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
// constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
@SuppressWarnings("rawtypes")
NamingEnumeration en = ctx.search("", "uid=" + usr + "",
constraints); // 查询所有用户
while (en != null && en.hasMoreElements()) {
Object obj = en.nextElement();
if (obj instanceof SearchResult) {
SearchResult si = (SearchResult) obj;
Attributes attrs = si.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);
boolean success = LdapUtil.verifySHA(pwd2, pwd);
if (success) {
attr = attrs.get("cn");
System.out.println("name:" + usr + " 验证成功!");
return attr.toString().split(" ")[1];
} else {
System.out.println("name:" + usr + " 密码错误!");
return "1"; // 密码不正确
}
}
} else {
System.out.println(obj);
}
}
System.out.println("无此用户 :" + usr + "");
ctx.close();
} catch (NoSuchAlgorithmException ex) {
try {
ctx.close();
} catch (NamingException namingException) {
namingException.printStackTrace();
}
} catch (NamingException ex) {
try {
ctx.close();
} catch (NamingException namingException) {
namingException.printStackTrace();
}
}
}
return "-1";}
public static void main(String[] args) {
try {
checkUser(
"sunsz",
"meimima",
connectLDAP("192.168.1.242", "389", "ldap", "12345",
"dc=times,dc=home"));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
【java工具类】LDAPUtil
最新推荐文章于 2021-02-25 22:16:42 发布