原因是ASP.NET Core MVC中MD5加密时会补全输入值,导致与在线MD5生成器不一致。可以采取以下方法解决:
使用在线MD5生成器时也进行值补全。
自定义ASP.NET Core MVC中的MD5加密方法,不进行值补全。
下面是第二种解决方法的示例代码:
using System.Security.Cryptography;
using System.Text;
public static class Md5Helper
{
public static string GetMd5Hash(string input)
{
using (var md5 = MD5.Create())
{
// 将输入转换为字节数组
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
// 进行MD5哈希计算
byte[] hashBytes = md5.ComputeHash(inputBytes);
// 将哈希后的字节数组转换为字符串
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
}
使用方法:
string input = "Hello World";
string md5Hash = Md5Helper.GetMd5Hash(input);
这样生成的MD5哈希值就与在线MD5生成器一致了。