在 C# 中实现 MD5 加密非常简单,.NET Framework 和 .NET Core 都提供了内置的加密类来处理哈希算法。MD5 虽然安全性较低,不推荐用于敏感数据(如密码存储),但在校验文件完整性、生成唯一标识等场景中仍被广泛使用。
1. 使用 System.Security.Cryptography.MD5 进行字符串加密
要对字符串进行 MD5 加密,需要将字符串转换为字节数组,然后通过 MD5 类计算哈希值,最后将哈希结果转换为十六进制字符串。
示例代码:
using System;
using System.Security.Cryptography;
using System.Text;
<p>public static string ComputeMD5(string input)
{
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);</p><pre class="brush:php;toolbar:false;"> // 将哈希字节数组转换为十六进制字符串
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2")); // x2 表示小写十六进制
}
return sb.ToString();
}}
// 使用示例 string source = "Hello, World!"; string md5Hash = ComputeMD5(source); Console.WriteLine($"MD5 哈希值: {md5Hash}");
2. 对文件进行 MD5 校验
除了字符串,还可以对整个文件内容进行 MD5 计算,常用于验证文件是否被修改或下载完整。
示例代码:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
<p>public static string ComputeFileMD5(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException("文件未找到", filePath);</p><pre class="brush:php;toolbar:false;">using (MD5 md5 = MD5.Create())
using (FileStream stream = File.OpenRead(filePath))
{
byte[] hashBytes = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}}
// 使用示例 try { string fileHash = ComputeFileMD5(@"C:\example.txt"); Console.WriteLine($"文件 MD5: {fileHash}"); } catch (Exception ex) { Console.WriteLine($"错误: {ex.Message}"); }
3. 注意事项与安全建议
尽管 MD5 实现简单、速度快,但存在严重安全问题:
碰撞攻击:不同内容可能产生相同的 MD5 值,已被证明不安全。 不适合密码存储:应使用 bcrypt、scrypt 或 PBKDF2 等专用算法。 推荐替代方案:如需更安全的哈希,可使用 SHA256 或 SHA512。提示:若需更高安全性,可替换 MD5 为 SHA256:
using (SHA256 sha256 = SHA256.Create())
{
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
// 同样转为十六进制
}
基本上就这些。C# 的加密类设计统一,掌握 MD5 后很容易扩展到其他哈希或加密算法。
