.NET中实现MD5和SHA256加密可通过内置类完成,先将字符串转为字节数组,再调用相应哈希算法计算并转换为十六进制字符串,推荐SHA256用于高安全场景,且哈希不可逆。

在 .NET 中实现 MD5 和 SHA256 加密非常简单,.NET 提供了内置的加密类来完成这些操作。下面介绍如何使用 C# 实现字符串的 MD5 和 SHA256 哈希加密。
MD5 加密实现
MD5 是一种广泛使用的哈希算法,虽然安全性较低,不推荐用于敏感数据保护,但在校验数据完整性等场景仍有使用。
使用 System.Security.Cryptography.MD5 类可以生成 MD5 哈希值:
- 将字符串转换为字节数组
- 调用 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);
string hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); Console.WriteLine("MD5: " + hashString);}
SHA256 加密实现
SHA256 是更安全的哈希算法,推荐用于密码存储、数字签名等需要高安全性的场景。
使用 System.Security.Cryptography.SHA256 类进行哈希计算:
示例代码:
using System; using System.Security.Cryptography; using System.Text;string input = "Hello, World!"; 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")); } Console.WriteLine("SHA256: " + sb.ToString());}
封装成通用方法
为了方便重复使用,可以将两个算法封装成静态方法:
public static class HashHelper { public static string GetMD5(string text) { using (MD5 md5 = MD5.Create()) { byte[] bytes = Encoding.UTF8.GetBytes(text); byte[] hash = md5.ComputeHash(bytes); return BitConverter.ToString(hash).Replace("-", "").ToLower(); } }public static string GetSHA256(string text) { using (SHA256 sha256 = SHA256.Create()) { byte[] bytes = Encoding.UTF8.GetBytes(text); byte[] hash = sha256.ComputeHash(bytes); StringBuilder sb = new StringBuilder(); foreach (byte b in hash) sb.Append(b.ToString("x2")); return sb.ToString(); } }}
调用方式:
Console.WriteLine(HashHelper.GetMD5("test")); Console.WriteLine(HashHelper.GetSHA256("test"));基本上就这些,.NET 的加密类设计简洁,使用起来很方便。注意哈希是单向过程,不能解密。如果需要加密解密功能,应使用对称或非对称加密算法如 AES 或 RSA。










