java ldap用戶密碼md5加密

在這裏不過多介紹ldap,由於這樣的文章特別多,這裏就簡單直接的記錄這一個問題。java

在springboot中經過引入spring-boot-starter-data-ldap,使用LdapTemplate真的挺方便,如今遇到一個問題,添加用戶時,userPasswod在ldap中顯示的是明文密碼,我如今要對這個userPassword加密.spring

而咱們不作任何設置查看源碼發現默認使用的是simplespringboot

 1 public class SimpleDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy {  2     private static final String SIMPLE_AUTHENTICATION = "simple";  3 
 4     public SimpleDirContextAuthenticationStrategy() {  5  }  6 
 7     public void setupEnvironment(Hashtable<String, Object> env, String userDn, String password) {  8         env.put("java.naming.security.authentication", "simple");  9         env.put("java.naming.security.principal", userDn); 10         env.put("java.naming.security.credentials", password); 11     }

再看源碼中也有DIGEST-MD5方式加密,可是找了半天不知道怎麼配置才能調用,搜索也沒發現他有引用這個類的地方。app

查看springboot官網有沒有相關配置,告訴能夠配置spring.ldap.base-environment,因此就配置了spring-boot

spring.ldap.base-environment.java.naming.security.authentication=DIGEST-MD5加密

最後跟代碼發現仍是會調用SimpleDirContextAuthenticationStrategy,並且配置的變量又會被從新定義成simple。spa

 1 public class DigestMd5DirContextAuthenticationStrategy implements DirContextAuthenticationStrategy {  2     private static final String DIGEST_MD5_AUTHENTICATION = "DIGEST-MD5";  3 
 4     public DigestMd5DirContextAuthenticationStrategy() {  5  }  6 
 7     public DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) {  8         return ctx;  9  } 10 
11     public void setupEnvironment(Hashtable<String, Object> env, String userDn, String password) { 12         env.put("java.naming.security.authentication", "DIGEST-MD5"); 13         env.put("java.naming.security.principal", userDn); 14         env.put("java.naming.security.credentials", password); 15  } 16 }

通過各類查官網,看源碼,都不行,而後就研究ldap,看ldap怎麼加密碼的,發現ldap有一條命令能夠返回md5加密碼,而後拿這個加密密碼存入userPasswod,再登陸是能夠的,因此只要我知道它是怎麼加密的,我也按這種方式加密,ldap就能夠解密。code

1 [root@alone ~]#  slappasswd -h {md5} -s "x1"
2 {MD5}bb+awtoJ7h096/WlGHPsbQ==

 

 

 

ldap md5加密代碼以下:blog

 1   /**
 2  * ldap md5加密  3  * @param str  4  * @return
 5  * @throws NoSuchAlgorithmException  6  * @throws UnsupportedEncodingException  7      */
 8     public static String LdapEncoderByMd5(String psw) throws NoSuchAlgorithmException, UnsupportedEncodingException {  9         MessageDigest md5=MessageDigest.getInstance("MD5"); 10         BASE64Encoder base64en = new BASE64Encoder(); 11         String md5psw=base64en.encode(md5.digest(psw.getBytes("utf-8"))); 12         return "{MD5}"+ md5psw; 13     }
相關文章
相關標籤/搜索