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

在 .NET 中实现 MD5 和 SHA256 加密非常简单,.NET 提供了内置的加密类来完成这些操作。下面介绍如何使用 C# 实现字符串的 MD5 和 SHA256 哈希加密。
MD5 是一种广泛使用的哈希算法,虽然安全性较低,不推荐用于敏感数据保护,但在校验数据完整性等场景仍有使用。
使用 System.Security.Cryptography.MD5 类可以生成 MD5 哈希值:
示例代码:
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;"><pre class="brush:php;toolbar:false;">string hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Console.WriteLine("MD5: " + hashString);}
SHA256 是更安全的哈希算法,推荐用于密码存储、数字签名等需要高安全性的场景。
使用 System.Security.Cryptography.SHA256 类进行哈希计算:
示例代码:
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;"><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;"><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。
以上就是.NET怎么实现MD5和SHA256加密的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号