在C#开发中,SHA256加密是处理数据哈希校验、敏感信息存储的常用手段,它属于SHA-2系列哈希算法,生成的哈希值长度为256位,安全性远高于早期的MD5算法,且哈希结果不可逆,无法直接反推原始数据。实现SHA256加密主要依赖.NET框架内置的System.Security.Cryptography命名空间下的相关类,无需额外引入第三方依赖。

核心命名空间与类说明
实现SHA256加密需要引入以下命名空间:
System.Security.Cryptography:包含SHA256相关的加密类System.Text:用于处理字符串到字节流的转换
核心类是SHA256抽象类,通常使用其派生类SHA256Managed或者SHA256CryptoServiceProvider,也可以通过SHA256.Create()工厂方法获取实例,这种方式会自动选择当前环境最优的实现。
基础字符串SHA256加密实现
对普通字符串进行SHA256加密是最常用的场景,整体流程分为三步:将字符串转换为字节数组、调用SHA256算法计算哈希、将哈希字节数组转换为可读的十六进制字符串。以下是完整实现代码:
using System;
using System.Security.Cryptography;
using System.Text;
public class SHA256Helper
{
/// <summary>
/// 对字符串进行SHA256加密,返回十六进制格式的哈希值
/// </summary>
/// <param name="input">待加密的原始字符串</param>
/// <returns>小写的十六进制哈希字符串</returns>
public static string EncryptStringToSHA256(string input)
{
if (string.IsNullOrEmpty(input))
{
throw new ArgumentException("待加密字符串不能为空");
}
// 将字符串转换为UTF8编码的字节数组
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
// 创建SHA256实例
using (SHA256 sha256 = SHA256.Create())
{
// 计算哈希值
byte[] hashBytes = sha256.ComputeHash(inputBytes);
// 将字节数组转换为十六进制字符串
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
// 格式化为两位十六进制,不足两位补0
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
}
调用上述方法的示例:
class Program
{
static void Main(string[] args)
{
string originalText = "test123456";
string encryptedText = SHA256Helper.EncryptStringToSHA256(originalText);
Console.WriteLine($"原始字符串:{originalText}");
Console.WriteLine($"SHA256加密结果:{encryptedText}");
}
}
字节流数据的SHA256加密
如果需要对文件、网络流等字节流数据进行SHA256加密,可以使用ComputeHash(Stream)重载方法,避免将全部数据加载到内存中,适合处理大体积数据。以下是文件SHA256校验的实现代码:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class FileSHA256Helper
{
/// <summary>
/// 计算文件的SHA256哈希值
/// </summary>
/// <param name="filePath">文件完整路径</param>
/// <returns>十六进制哈希字符串</returns>
public static string GetFileSHA256(string filePath)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException("目标文件不存在", filePath);
}
using (SHA256 sha256 = SHA256.Create())
{
// 以只读方式打开文件流
using (FileStream fileStream = File.OpenRead(filePath))
{
// 计算流的哈希值
byte[] hashBytes = sha256.ComputeHash(fileStream);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
}
}
注意事项
- SHA256是哈希算法而非加密算法,哈希结果不可逆,无法从哈希值反推原始数据,因此适合做数据校验、密码存储,不适合做需要解密的数据加密。
- 加密前字符串的编码必须统一,推荐使用UTF8编码,避免因编码不同导致相同的原始字符串生成不同的哈希值。
- 使用完
SHA256实例后需要及时释放资源,建议使用using语句自动管理生命周期,避免内存泄漏。 - 如果需要存储密码,建议结合盐值(Salt)使用,避免相同密码生成相同哈希值被彩虹表破解,盐值需要和哈希值一起存储。
带盐值的密码哈希实现
以下是结合随机盐值的密码SHA256哈希实现,更符合实际密码存储的安全要求:
using System;
using System.Security.Cryptography;
using System.Text;
public class SaltedSHA256Helper
{
/// <summary>
/// 生成带盐值的密码哈希
/// </summary>
/// <param name="password">原始密码</param>
/// <param name="salt">输出的盐值,Base64格式</param>
/// <returns>带盐值的哈希结果,Base64格式</returns>
public static string HashPasswordWithSalt(string password, out string salt)
{
// 生成16字节的随机盐值
byte[] saltBytes = new byte[16];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(saltBytes);
}
salt = Convert.ToBase64String(saltBytes);
// 将密码和盐值拼接后计算哈希
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] combinedBytes = new byte[passwordBytes.Length + saltBytes.Length];
Buffer.BlockCopy(passwordBytes, 0, combinedBytes, 0, passwordBytes.Length);
Buffer.BlockCopy(saltBytes, 0, combinedBytes, passwordBytes.Length, saltBytes.Length);
using (SHA256 sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(combinedBytes);
return Convert.ToBase64String(hashBytes);
}
}
/// <summary>
/// 验证密码和存储的哈希是否匹配
/// </summary>
public static bool VerifyPassword(string password, string storedSalt, string storedHash)
{
byte[] saltBytes = Convert.FromBase64String(storedSalt);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] combinedBytes = new byte[passwordBytes.Length + saltBytes.Length];
Buffer.BlockCopy(passwordBytes, 0, combinedBytes, 0, passwordBytes.Length);
Buffer.BlockCopy(saltBytes, 0, combinedBytes, passwordBytes.Length, saltBytes.Length);
using (SHA256 sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(combinedBytes);
string currentHash = Convert.ToBase64String(hashBytes);
return currentHash == storedHash;
}
}
}
C#SHA256_encrypthash_algorithmencoding修改时间:2026-06-21 06:33:19