在 .NET 中实现 MD5 和 SHA256 加密可通过内置类完成,1. 使用 System.Security.Cryptography.MD5 计算字符串哈希,将输入字符串转为 UTF-8 字节数组并生成哈希值,再转换为小写十六进制字符串;2. 使用 SHA256 类进行更安全的哈希计算,适用于密码存储等高安全场景;3. 注意哈希不可逆,应配合盐值使用 SHA256 或更强算法如 PBKDF2;4. 可封装为静态工具类提高复用性。

在 .NET 中实现 MD5 和 SHA256 加密非常简单,.NET 提供了内置的加密类来处理常见的哈希算法。下面介绍如何使用 C# 实现字符串的 MD5 和 SHA256 哈希加密。
MD5 是一种广泛使用的哈希算法,虽然不推荐用于高安全性场景(如密码存储),但在校验数据完整性等场景中仍有应用。
在 .NET 中,使用 System.Security.Cryptography.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"));
}
return sb.ToString();
}}
调用方式:
string result = ComputeMD5("Hello World");
Console.WriteLine(result); // 输出: b10a8db164e0754105b7a99be72e3fe5
SHA256 是比 MD5 更安全的哈希算法,推荐用于需要较高安全性的场景,比如用户密码哈希(配合盐值)。
使用 System.Security.Cryptography.SHA256 类实现。
示例代码:
using System;
using System.Security.Cryptography;
using System.Text;
<p>public static string ComputeSHA256(string input)
{
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();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}}
调用方式:
string result = ComputeSHA256("Hello World");
Console.WriteLine(result);
// 输出: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e
哈希是单向过程,不能解密。适用于验证数据完整性或存储密码摘要。
你可以将上述方法封装到一个静态工具类中,便于复用:
public static class HashHelper
{
public static string MD5(string input) { /* 如上实现 */ }
public static string SHA256(string input) { /* 如上实现 */ }
}
基本上就这些。.NET 的加密支持很完善,使用起来也很直观。只要注意安全实践,就能正确使用 MD5 和 SHA256。
以上就是.NET怎么实现MD5和SHA256加密_MD5 SHA256加密实现教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号