有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在开发一个登录框架,该框架检查用户输入的密码与SQL数据库中的密码。我将文本转换为MD5以存储在数据库中,如下所示

产生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

我做错了什么

编辑:我不相信这是一个重复,因为我已经研究了答案,它已经让我走了这么远,但我不能找出我做错了什么


共 (1) 个答案

  1. # 1 楼答案

    只需将基数参数传递给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();
    }