关于java 操作LDAP 查询/修改/加密

前提:  pom添加相关jar包依赖

<!--    LDAP的增删改查    -->
        <!-- https://mvnrepository.com/artifact/com.novell.ldap/jldap -->
        <dependency>
            <groupId>com.novell.ldap</groupId>
            <artifactId>jldap</artifactId>
            <version>2009-10-07</version>
        </dependency>

1. 获取用户的DN

例如用户:  cn=zhangsan  

结果:  cn=zhangsan,ou=Student,ou=Person,dc=Baidu,dc=com

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jhr.linuxcomand.LDAP.MD5Test;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.security.MessageDigest;
import java.util.Hashtable;
import java.util.Vector;

public class LdapHelper {

    private final String URL = "ldap://127.0.0.1:389/";
    private final String BASEDN = "";  // 根据自己情况进行修改
    private final String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    private LdapContext ctx = null;
    private final Control[] connCtls = null;

    private void LDAP_connect() {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
        env.put(Context.PROVIDER_URL, URL + BASEDN);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        String root = "cn=admin,dc=Baidu,dc=com";  //根据自己情况修改
        env.put(Context.SECURITY_PRINCIPAL, root);   // 管理员
        env.put(Context.SECURITY_CREDENTIALS, "adminPassword");  // 管理员密码

        try {
            ctx = new InitialLdapContext(env, connCtls);
            System.out.println("连接成功:");

        } catch (AuthenticationException e) {
            System.out.println("连接失败:{}"+e.getMessage());
        } catch (Exception e) {
            System.out.println("连接出错:{}"+e.getMessage());
        }

    }

    private void closeContext() {
        if (ctx != null) {
            try {
                ctx.close();
                System.out.println("关闭连接成功!");
            } catch (NamingException e) {
                e.printStackTrace();
            }

        }
    }


    //根据人名模糊查询ldap
    public String getUserCnSn(String name, String account) {
        String filter = "(objectclass=*)";
        if ((name != null && !"".equals(name)) && (account == null || "".equals(account))) {
            filter = "sn=*" + name + "*";
            System.out.println("查找用户,sn={}"+ name);
        }
        if ((account != null && !"".equals(account)) && ((name == null || "".equals(name)))) {
            filter = "cn=" + account;
            System.out.println("查找用户,cn={}"+ account);
        }
        LDAP_connect();
        String userDN = "";
        try {
            SearchControls constraints = new SearchControls();
            String[] attrIDs = {"cn", "sn", "mail", "entryDN"};

            constraints.setReturningAttributes(attrIDs);
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> en = ctx.search("dc=tydic,dc=com", filter, constraints);
            if (en == null || !en.hasMoreElements()) {
                System.out.println("未找到该用户");
            }
            // maybe more than one element
            while (en != null && en.hasMoreElements()) {
                Object obj = en.nextElement();
                if (obj instanceof SearchResult) {
                    SearchResult si = (SearchResult) obj;
                    Attributes attributes = si.getAttributes();
                    Attribute attsn = attributes.get("sn");
                    Attribute attcn = attributes.get("cn");
                    Attribute attmail = attributes.get("mail");
                    Attribute dn = attributes.get("entryDN");
                    if (attsn != null && attcn != null) {
                        try {
                            //捕获有的人没有邮箱等的错误
                            userDN = dn.toString().replace("entryDN:", "").trim();
                        } catch (Exception e) {
                        }
                    }
                } else {
                    System.out.println("{}"+ obj);
                }
            }
        } catch (Exception e) {
            System.out.println("查找用户时产生异常:{}"+ e.getMessage());
        }finally {
            closeContext();
        }

        return userDN;
    }


    public static void main(String[] args) {

        //查询
        String r = new LdapHelper().getUserCnSn("", "zhangsan");
        System.out.println(r);


    }

}

2. 修改用户属性值(objectClass =inetOrgPerson )

例如:以下是修改用户密码(userpassword 属性的值)

在上面的基础上  添加修改方法:

 public void updateAttributes(String name, int mod_op, Attributes attrs){
        try {
            LDAP_connect();
            ctx.modifyAttributes(name,mod_op,attrs);
        } catch (NamingException e) {
            e.printStackTrace();
        }finally {
            closeContext();
        }
    }



public static void main(String[] args) {
      
        String pwdStr = "{SSHA}cMBICxEEbUj8W9uNp/9WO18a4cc0HWxo";
        Attributes attrs = new BasicAttributes("userPassword", pwdStr);

        new LdapHelper().updateAttributes(r,DirContext.REPLACE_ATTRIBUTE,attrs);


    }

LDAP 的增删改查 的第二种方式https://blog.csdn.net/lettuce_/article/details/105247591 

 

3. 关于LDAP用户密码user  密文的生成方式

SSHA加密参考:https://blog.csdn.net/qq_40625030/article/details/104302662

public class test01 {
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String pwd= RandomStringUtils.randomAlphanumeric(8);
        System.out.println(pwd);
 
        String s = generateSSHAPwd(pwd);
        System.out.println(s);
    }
 
    /**
     * Openldap 产生SSHA密码的算法
     * 效果等同于 slappasswd -h {ssha} -s password
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String generateSSHAPwd(String password)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final int SALT_LENGTH = 4;
        SecureRandom secureRandom = new SecureRandom();
        byte[] salt = new byte[SALT_LENGTH];
        secureRandom.nextBytes(salt);
 
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(password.getBytes("utf-8"));
        crypt.update(salt);
        byte[] hash = crypt.digest();
 
        byte[] hashPlusSalt = new byte[hash.length + salt.length];
        System.arraycopy(hash, 0, hashPlusSalt, 0, hash.length);
        System.arraycopy(salt, 0, hashPlusSalt, hash.length, salt.length);
 
        return new StringBuilder().append("{SSHA}")
                .append(new String(Base64.encodeBase64(hashPlusSalt), Charset.forName("utf-8")))
                .toString();
    }
 
}

 

MD5 加密参考:

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Test {
    public static void main(String[] args) {
        try {
            String psw = "123456";
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            String md5psw=base64en.encode(md5.digest(psw.getBytes("utf-8")));
            System.out.println(md5psw);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值