0

我尝试使用 Java 获取 MD5 字符串,但下面的函数返回字符串"MD5 Message Digest from SUN, <in progress>"

public String hash(String value) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(value.getBytes("UTF-8"));
        return md.toString();
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

我在 Xubuntu 上使用 OpenJDK。为什么我会收到此消息?有没有办法使用此设置获取 MD5 哈希?

4

2 回答 2

2

我找到了有效的解决方案,

public String byteToHexString(byte[] input) {
    String output = "";
    for (int i=0; i<input.length; ++i) {
        output += String.format("%02X", input[i]);
    }
    return output;
}

public String hash(String value) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        return byteToHexString(md.digest(value.getBytes("UTF-8")));
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
于 2013-12-04T07:38:48.477 回答
0

一种选择是使用commons-codec.jar。检查API

String value = "YourValue";
System.out.println(DigestUtils.md5Hex( value ));
于 2013-12-03T18:02:50.550 回答