在C#中对字符串进行SHA256加密,本质上是调用.NET内置的SHA256托管算法,把原始文本转为固定长度的哈希值。这种做法常用于密码存储、接口签名和数据防篡改校验。下面先看一个基础示例。

基础字符串SHA256加密实现
最核心的步骤是:把字符串按指定编码转为字节数组,交给SHA256算法计算哈希,再把结果格式化为十六进制字符串。注意哈希不是可逆加密,无法还原原文。
using System;
using System.Security.Cryptography;
using System.Text;
public class Sha256Demo
{
// 对字符串做SHA256摘要,返回小写十六进制
public static string ComputeSha256(string input)
{
using (SHA256 sha256 = SHA256.Create())
{
// 将字符串按UTF8编码为字节
byte[] bytes = Encoding.UTF8.GetBytes(input);
// 计算哈希
byte[] hashBytes = sha256.ComputeHash(bytes);
// 字节转十六进制
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
public static void Main()
{
string text = "hello world";
string result = ComputeSha256(text);
Console.WriteLine(result);
}
}
为什么要加盐
如果直接对密码做SHA256,相同密码总会得到相同摘要,容易被彩虹表攻击。更安全的做法是拼接随机盐值后再哈希。
带盐值的写法
using System;
using System.Security.Cryptography;
using System.Text;
public class SaltedSha256
{
public static string HashWithSalt(string password, string salt)
{
using (SHA256 sha256 = SHA256.Create())
{
string mixed = password + salt;
byte[] bytes = Encoding.UTF8.GetBytes(mixed);
byte[] hash = sha256.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
}
常见注意点
- 推荐使用UTF8编码,避免中文在不同环境乱码
- SHA256算出的字节长度是32,十六进制字符串为64位
- 不要自己造哈希算法,始终用.NET提供的
SHA256.Create() - 密码场景优先用PBKDF2或bcrypt,SHA256更适合校验而非存密码
小结
用C#做字符串SHA256加密并不复杂,关键在编码一致、结果正确转十六进制,以及根据场景决定是否加盐。理解这些后,你就能在签名、去重、完整性检查中安全使用SHA256摘要。
C#SHA256string_hash修改时间:2026-07-28 01:09:18