如何解决使JAVA MD5哈希匹配C#MD5哈希
我的工作是用C#重写一堆Java代码。 这是JAVA代码:
public static String CreateMD5(String str) {
try {
byte[] digest = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
for (byte b : digest) {
// i can not understand here
stringBuffer.append(Integer.toHexString((b & 255) | 256).substring(1,3));
}
return stringBuffer.toString();
} catch (UnsupportedEncodingException | NoSuchAlgorithmException unused) {
return null;
}
}
好吧,正如您所看到的那样,这段代码正在尝试使MD5散列。但是我无法理解的是我所展示的部分。 我在C#中尝试了以下代码以重写此JAVA代码:
public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
两个代码都在制作MD5哈希字符串,但结果不同。
解决方法
您显示的两个代码段之间的编码有所不同-Java代码使用UTF-8,而C#代码使用ASCII。这将导致不同的MD5哈希计算。
从以下位置更改C#代码:
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
收件人:
byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
只要没有其他代码转换错误,此应该™即可解决您的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。