C#怎么进行MD5加密 C#计算字符串和文件的MD5哈希值

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

在C#中计算MD5哈希值是常见的需求,常用于校验数据完整性或生成唯一标识。.NET 提供了 System.Security.Cryptography.MD5 类来实现字符串和文件的MD5加密。

计算字符串的MD5哈希值

要对字符串进行MD5加密,需要先将字符串转换为字节数组,然后使用MD5类计算哈希值,最后将结果转换为十六进制字符串。

  • 使用 Encoding.UTF8.GetBytes() 将字符串转为字节流
  • 调用 MD5.ComputeHash() 计算哈希值
  • 将哈希字节数组格式化为小写十六进制字符串

示例代码:

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哈希值

对于大文件,直接读取全部内容会影响性能,因此推荐使用流式处理。MD5类支持从文件流中逐块读取并计算哈希值。

  • 使用 FileStream 打开文件
  • 调用 MD5.ComputeHash(stream) 自动处理分块读取
  • 确保文件流被正确释放(使用 using)

示例代码:

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 或更高强度的哈希算法。