在 .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;
<p>string input = "Hello, World!";
using (MD5 md5 = MD5.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);</p><pre class="brush:php;toolbar:false;">string hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Console.WriteLine("MD5: " + hashString);}
SHA256 加密实现
SHA256 是更安全的哈希算法,推荐用于密码存储、数字签名等需要高安全性的场景。
使用 System.Security.Cryptography.SHA256 类进行哈希计算:
同样先将字符串编码为字节 调用 SHA256.ComputeHash() 获取哈希结果 格式化输出为小写十六进制字符串示例代码:
using System;
using System.Security.Cryptography;
using System.Text;
<p>string input = "Hello, World!";
using (SHA256 sha256 = SHA256.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = sha256.ComputeHash(inputBytes);</p><pre class="brush:php;toolbar:false;">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();
}
}
<pre class="brush:php;toolbar:false;">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。
