https://blog.csdn.net/KENT_/article/details/3899754
正在做一个项目,在验证登录用户密码的时候,需要用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);
}
调整后:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
/** * https://blog.csdn.net/KENT_/article/details/3899754 * * @param password * @return * @throws java.security.NoSuchAlgorithmException */ public static String ldapMd5EncodePassword(String password) throws NoSuchAlgorithmException { byte[] unencodedPassword = password.getBytes(); final java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.reset(); md.update(unencodedPassword); byte[] encodedPassword = md.digest(); final StringBuilder buf = new StringBuilder(); 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)); } final StringBuilder sb = new StringBuilder(); sb.append("{MD5}").append(Base64.getEncoder().encodeToString(ba)); return sb.toString(); } |