尝试将字符串转换为 MD5 时我做错了什么

What am I doing wrong when trying to convert string to MD5

我正在开发一个登录框架,用于根据 SQL 数据库中的密码检查用户输入的密码。我将文本转换为 MD5 以使用以下内容存储在数据库中

HASHBYTES('MD5', 'JavaTest') 生成 5E58D71FBD6D17577AAAB8711264A813。

然后在 java 中,我使用以下代码尝试将相同的密码 "JavaTest" 转换为 MD5 以进行比较。

MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(password.getBytes());
            byte[] digest = m.digest();
            BigInteger bigInt = new BigInteger(1, digest);
            hashText = bigInt.toString();

但这会产生字符串 150157350912923000195076232128194914284

我做错了什么?

编辑:我不认为这是重复的,因为我已经研究了答案并且它已经让我走了这么远,但我无法弄清楚我做错了什么。

只需将基数参数传递给bigInt.toString。如果你需要十六进制表示,像这样将 16 作为基数传递:

hashText = bigInt.toString(16);

public String toString(int radix)

Returns the String representation of this BigInteger in the given radix. If the radix is outside the range from Character.MIN_RADIX to Character.MAX_RADIX inclusive, it will default to 10 (as is the case for Integer.toString). The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate. (This representation is compatible with the (String, int) constructor.)

Parameters:

radix - radix of the String representation. Returns: String representation of this BigInteger in the given radix.

此外,您可以像这样在不使用 BigInteger 的情况下构建十六进制字符串形式的摘要字节数组:

public static String bytesToHex(byte[] bytes) {
    StringBuilder builder = new StringBuilder();
    for(byte b : bytes) {
        builder.append(String.format("%02x", b));
    }
    return builder.toString();
}