C# (.NET) 中的密码学:加密与哈希
数据安全是现代开发中的关键任务之一。.NET 平台在 System.Security.Cryptography 命名空间中提供了一套强大且灵活的加密保护工具。本文将详细解析 C# 中密码学的主要功能:对称与非对称加密,以及数据哈希。无论您是初学者还是希望系统化知识的有经验开发者,本文都将对您有所帮助。
1. 主要命名空间和类
所有加密功能都集中在 System.Security.Cryptography 程序集中。关键类包括:
Aes、DES、TripleDES—— 对称算法;RSA、ECDsa、ECDiffieHellman—— 非对称算法;SHA256、SHA512、MD5—— 哈希算法;RandomNumberGenerator—— 加密安全的随机数生成器。
重要提示:请仅使用现代算法。MD5 和 SHA1 已过时,且对于加密目的而言不安全。
2. 对称加密 (AES)
对称加密使用相同的密钥进行加密和解密。最流行的算法是 AES(高级加密标准)。我们来看一个字符串加密的示例。
using System;using System.IO;using System.Security.Cryptography;using System.Text;
public class AesEncryption{ public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv) { using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } return msEncrypt.ToArray(); } } } }
public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] key, byte[] iv) { using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { return srDecrypt.ReadToEnd(); } } } } }}要生成安全的密钥和初始化向量 (IV),请使用 RandomNumberGenerator:
using System.Security.Cryptography;
byte[] key = new byte[32]; // 256 位byte[] iv = new byte[16]; // 128 位using (RandomNumberGenerator rng = RandomNumberGenerator.Create()){ rng.GetBytes(key); rng.GetBytes(iv);}3. 非对称加密 (RSA)
非对称加密使用一对密钥:公钥和私钥。RSA 是一种经典算法,适用于加密少量数据(通常对于 2048 位密钥,最多约 190 字节)。示例:
using System;using System.Security.Cryptography;using System.Text;
public class RsaEncryption{ public static (byte[]