C#中使用System.Security.Cryptography.MD5类计算字符串和文件的MD5哈希值,需将字符串转为字节数组后调用ComputeHash方法,并将结果转为十六进制字符串;对于文件则通过FileStream流式读取以提升性能;推荐封装为静态工具方法以便复用;但MD5不适用于安全敏感场景,建议改用SHA256。

在C#中计算MD5哈希值是常见的需求,常用于校验数据完整性或生成唯一标识。.NET 提供了 System.Security.Cryptography.MD5 类来实现字符串和文件的MD5加密。
要对字符串进行MD5加密,需要先将字符串转换为字节数组,然后使用MD5类计算哈希值,最后将结果转换为十六进制字符串。
示例代码:
using System;
using System.Security.Cryptography;
using System.Text;
string input = "Hello, World!";
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// 转为16进制字符串
string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Console.WriteLine(hash); // 输出: 65a8e27d8879283831b664bd8b7f0ad4
}对于大文件,直接读取全部内容会影响性能,因此推荐使用流式处理。MD5类支持从文件流中逐块读取并计算哈希值。
示例代码:
using System;
using System.IO;
using System.Security.Cryptography;
string filePath = @"C:\example.txt";
using (var md5 = MD5.Create())
using (var stream = File.OpenRead(filePath))
{
byte[] hashBytes = md5.ComputeHash(stream);
string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Console.WriteLine(hash);
}为了方便使用,可以将字符串和文件的MD5计算封装为静态方法。
public static class MD5Helper
{
public static string GetMd5Hash(string input)
{
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
}
public static string GetFileMd5(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException("文件未找到", filePath);
using (var md5 = MD5.Create())
using (var stream = File.OpenRead(filePath))
{
byte[] hashBytes = md5.ComputeHash(stream);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
}
}调用方式:
Console.WriteLine(MD5Helper.GetMd5Hash("test"));
Console.WriteLine(MD5Helper.GetFileMd5(@"C:\demo.txt"));基本上就这些。注意:MD5已不推荐用于安全敏感场景(如密码存储),因其存在碰撞风险。建议在安全性要求高的场合使用 SHA256 或更高强度的哈希算法。
以上就是C#怎么进行MD5加密 C#计算字符串和文件的MD5哈希值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号