package com.dsideal.sso.Util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.binary.Base64;

public class LdapPassWordEncoder {

    public String md5(String target) {
        return DigestUtils.md5Hex(target);
    }


    //算法：将密码经过 MD5 运算，得到 32 字节的字符串，然后每2个字节压缩成一个十六进制字符，这样得到16字节的字符串，最后经过Base64编码。
    public String getLdapPassword(String md5pass) {
        md5pass = md5(md5pass);
        try {
            byte[] baKeyword = new byte[md5pass.length() / 2];
            for (int i = 0; i < baKeyword.length; i++) {
                try {
                    baKeyword[i] = (byte) (0xff & Integer.parseInt(md5pass.substring(i * 2, i * 2 + 2), 16));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String newstr = Base64.encodeBase64String(baKeyword);
            return newstr;
        } catch (Exception err) {
            System.out.println("出错的密码：" + md5pass);
            return null;
        }
    }
}
