哈希算法用于将数据转换为固定长度的哈希值(不可逆),常用于密码存储、文件校验。
using System.Security.Cryptography;
using System.Text;
public class HashHelper
{
// 计算MD5哈希值(32位小写)
public static string ComputeMD5(string input)
{
if (string.IsNullOrEmpty(input)) return "";
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// 转换为16进制字符串
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
// 计算SHA256哈希值(64位小写)
public static string ComputeSHA256(string input)
{
if (string.IsNullOrEmpty(input)) return "";
using (SHA256 sha256 = SHA256.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = sha256.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
}
// 调用示例
string password = "123456";
string md5Hash = HashHelper.ComputeMD5(password);
string sha256Hash = HashHelper.ComputeSHA256(password);
Console.WriteLine($"密码:{password}");
Console.WriteLine($"MD5哈希(32位):{md5Hash}");
Console.WriteLine($"SHA256哈希(64位):{sha256Hash}");
// 输出:
// 密码:123456
// MD5哈希(32位):e10adc3949ba59abbe56e057f20f883e
// SHA256哈希(64位):8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
注意:MD5 安全性较低,建议用于非敏感数据校验;密码存储建议使用 SHA256 + 盐值(Salt)。