首先使用System.Security.Cryptography.MD5对字符串或文件进行哈希计算,字符串需先转为字节数组,文件则通过FileStream读取,结果均转换为小写十六进制字符串;但MD5存在碰撞风险,不适用于密码存储,推荐改用SHA256或更高安全算法。

在 C# 中实现 MD5 加密非常简单,.NET Framework 和 .NET Core 都提供了内置的加密类来处理哈希算法。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;"><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}");
除了字符串,还可以对整个文件内容进行 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;"><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}"); }
尽管 MD5 实现简单、速度快,但存在严重安全问题:
提示:若需更高安全性,可替换 MD5 为 SHA256:
using (SHA256 sha256 = SHA256.Create())
{
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
// 同样转为十六进制
}
基本上就这些。C# 的加密类设计统一,掌握 MD5 后很容易扩展到其他哈希或加密算法。
以上就是C# 怎么进行 MD5 加密_C# MD5 加密实现教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号