MessageDigest MD5 Algorithm not returning what I expect

假装没事ソ 提交于 2019-12-03 07:24:42
ruakh

for example, according to this website, the string "hello" generates a hash of "5d41402abc4b2a76b9719d911017c592". (FWIW I don't know anything about this website except that it seems to correctly hash the examples that I have). When I run it through my code I get:

XUFAKrxLKna5cZ2REBfFkg==

Both are correct ways of representing the same sixteen-byte hash. 5d41402abc4b2a76b9719d911017c592 represents each byte of the hash as two hexadecimal digits, whereas XUFAKrxLKna5cZ2REBfFkg== uses Base-64 to represent every three bytes of the hash as four characters.

To generate the hexadecimal-version that this third-party API is expecting, you can change this:

Base64.encodeBase64String(md.digest());

to this:

String.format("%032x", new BigInteger(1, md.digest()));

(mostly taken from this StackOverflow answer).

However, you might want to consider using an external library for this. Perception, in a comment above, mentions Apache Commons DigestUtils. If you use that, you'll want the md5hex method.

The md5 Hash algorithm is part of the core java API so there is no need for any external libraries. Here is the method I used to encrypt a password with MD5.

import java.security.MessageDigest;

/**
 * Use to encrypt passwords using MD5 algorithm
 * @param password should be a plain text password.
 * @return a hex String that results from encrypting the given password.
 */
public static String encryptPassword(String password) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());

        byte byteData[] = md.digest();

        StringBuffer hexString = new StringBuffer();
        for (int i=0;i<byteData.length;i++) {
            String hex=Integer.toHexString(0xff & byteData[i]);
            if(hex.length()==1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
    catch(java.security.NoSuchAlgorithmException missing) {
        return "Error.";
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!