gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:35:23 30 4
gpt4 key购买 nike

我正在开发一个登录框架,用于根据 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();
}

关于java - 尝试将字符串转换为 MD5 时我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005159/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com