C# (.NET) 中的密码学:加密与哈希
数据安全是现代开发的关键方面之一。.NET 平台在 System.Security.Cryptography 命名空间中提供了强大且灵活的加密信息保护工具集。在本文中,我们将探讨 C# (.NET) 中密码学的主要功能:对称和非对称加密、密码哈希以及数字签名的创建。
1. 对称加密 (AES)
对称加密使用相同的密钥来加密和解密数据。最常用的算法是 AES(高级加密标准)。在 .NET 中,它由 Aes 类实现。
使用 AES 加密和解密字符串的示例:
using System;using System.IO;using System.Security.Cryptography;using System.Text;
public class AesExample{ 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(); } } } } }}2. 非对称加密 (RSA)
非对称加密使用一对密钥:公钥用于加密,私钥用于解密。在 .NET 中,此机制由 RSA 类实现。RSA 通常用于安全传输对称密钥。
使用 RSA 生成密钥和加密的示例:
using System;using System.Security.Cryptography;using System.Text;
public class RsaExample{ public static void RsaEncryptDecrypt() { using (RSA rsa = RSA.Create()) { // 生成密钥(2048 位) RSAParameters publicKey = rsa.ExportParameters(false); // 仅公钥 RSAParameters privateKey = rsa.ExportParameters(true); // 两个密钥
string original = "RSA 的秘密消息";
// 使用公钥加密 byte[] encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(original), RSAEncryptionPadding.OaepSHA256);
// 使用私钥解密 byte[] decryptedData = rsa.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA256); string decrypted = Encoding.UTF8.GetString(decryptedData);
Console.WriteLine($"原文: {original}"); Console.WriteLine($"解密后: {decrypted}"); } }}3. 数据哈希 (SHA-256, MD5)
哈希