正在做一个项目,在验证登录用户密码的时候,需要用java来实现LDAP的MD5算法,本以为网上会有很多这样的信息,上网找了一下,居然没找到。自己写一个留给大家,以后谁能用到好做个参考。代码如下:
public static String ldapMd5EncodePassword(String password) {
byte[] unencodedPassword = password.getBytes();
java.security.MessageDigest md = null;
try {
md = java.security.MessageDigest.getInstance("MD5");
} catch (Exception e) {
log.error("Exception: " + e);
return password;
}
md.reset();
md.update(unencodedPassword);
byte[] encodedPassword = md.digest();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < encodedPassword.length; i++) {
if ((encodedPassword[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
}
String standardMd5 = buf.toString();
byte[] ba = new byte[standardMd5.length()/2];
for (int i = 0; i < standardMd5.length(); i=i+2) {
ba[i == 0 ? 0 : i/2] = (byte) (0xff & Integer.parseInt(standardMd5.substring(i, i+2), 16));
}
return "{MD5}" + new sun.misc.BASE64Encoder().encode(ba);
}