在 Web 开发或系统构建中,处理敏感数据(如密码、支付信息)或验证数据完整性是核心任务。C# 提供了强大的 System.Security.Cryptography 命名空间,支持多种加密模型。
1. 哈希算法:不可逆加密 (MD5 & SHA)
哈希算法常用于数据签名或密码存储。它们将任意长度的数据映射为固定长度的摘要。
MD5 & SHA 实战
安全警示:MD5 和 SHA1 在碰撞攻击面前已不再安全,不建议用于存储用户密码。请优先使用 SHA256 或更高版本。
using System.Security.Cryptography;
using System.Text;
public static string ComputeHash(string input, string algorithm = "SHA256")
{
using HashAlgorithm hashAlg = algorithm switch
{
"MD5" => MD5.Create(),
"SHA1" => SHA1.Create(),
"SHA512" => SHA512.Create(),
_ => SHA256.Create()
};
byte[] data = hashAlg.ComputeHash(Encoding.UTF8.GetBytes(input));
return Convert.ToHexString(data); // .NET 5+ 推荐用法
}
2. 对称加密:AES & DES
对称加密使用同一个密钥进行加解密。AES 是目前的行业标准,而 DES 已被认为是不安全的。
AES 高安全性实现
下面的代码修复了常见错误:显式处理了 IV(初始化向量),这是防止重放攻击的关键。
public static string AesEncrypt(string plainText, byte[] key, out byte[] iv)
{
using Aes aes = Aes.Create();
aes.Key = key;
aes.GenerateIV(); // 自动生成随机 IV
iv = aes.IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using MemoryStream ms = new();
using (CryptoStream cs = new(ms, encryptor, CryptoStreamMode.Write))
using (StreamWriter sw = new(cs))
{
sw.Write(plainText);
}
return Convert.ToBase64String(ms.ToArray());
}
3. 非对称加密:RSA
RSA 使用公钥加密、私钥解密。常用于数字证书和跨服务器的安全握手。
public static string RSAEncrypt(string data, string xmlPublicKey)
{
using RSA rsa = RSA.Create();
rsa.FromXmlString(xmlPublicKey); // 注意:.NET Core 以上建议使用 PEM 格式
byte[] encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(data), RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(encryptedData);
}
4. 数据编码:Base64
注意:Base64 不是加密。它只是一种编码方式,任何人都可以在不使用密钥的情况下解码。它主要用于在文本协议(如 JSON)中传输二进制数据。
public static string Base64Encode(string plainText) =>
Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
💡 开发选型指南:我该用哪种算法?
| 需求场景 | 推荐算法 | 理由 |
|---|---|---|
| 存储用户密码 | BCrypt 或 Argon2 | 比单纯的 SHA 更能抵抗暴力破解。 |
| 大文件/常规数据加密 | AES-256-GCM | 速度快,安全性极高。 |
| HTTPS/数字签名 | RSA 或 ECDSA | 非对称特性支持公信验证。 |
| 校验文件是否被篡改 | SHA-256 | 相同文件必产生相同摘要。 |
总结
- 永远不要自己发明加密算法。
- 对称加密(AES)速度快,适合大量数据。
- 非对称加密(RSA)解决了密钥传输问题,但速度慢。
- 哈希(SHA)用于验证,不可还原。