核心概念
1. 什么是加密?
- 加密:加密是一種將數據轉換為一種不可讀形式的方法,只有持有相應密鑰的人才能解密并讀取數據。
- 目的:確保數據的機密性和安全性,特別是在傳輸過程中過防止未授權訪問。
2. 加密類型
對稱加密:
- 使用相同的密鑰進行加密和解密。
- 常見算法:AES、DES。
- 優點:速度快,適合大數據量加密。
非對稱加密:
- 使用公鑰加密和私鑰解密。
- 常見算法:RSA。
- 優點:安全性高,適合密鑰交換和數字簽名。
3. 散列函數
- 散列函數:又稱為哈希函數,將任意長度的數據轉換為固定長度的字符串。
- 特點:不可逆,常用于驗證數據完整性。
- 常見算法:MD5、SHA-256。
?實際使用
對稱加密示例:AES
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;public class AesEncryptionExample
{public static void Main(){string original = "Sensitive data that needs encryption";// 創建AES加密服務實例using (Aes aesAlg = Aes.Create()){// 加密字符串到字節數組byte[] encrypted = EncryptStringToBytes_Aes(original, aesAlg.Key, aesAlg.IV);// 解密字節數組回字符串string decrypted = DecryptStringFromBytes_Aes(encrypted, aesAlg.Key, aesAlg.IV);Console.WriteLine($"Original: {original}");Console.WriteLine($"Decrypted: {decrypted}");}}static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV){// 參數檢查if (plainText == null || plainText.Length <= 0)throw new ArgumentNullException(nameof(plainText));if (Key == null || Key.Length <= 0)throw new ArgumentNullException(nameof(Key));if (IV == null || IV.Length <= 0)throw new ArgumentNullException(nameof(IV));byte[] encrypted;// 使用AES算法using (Aes aesAlg = Aes.Create()){aesAlg.Key = Key; // 設置加密密鑰aesAlg.IV = IV; // 設置初始化向量// 創建一個加密器來執行流轉換ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);// 用內存流進行加密using (MemoryStream msEncrypt = new MemoryStream()){// 創建加密流using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)){using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)){swEncrypt.Write(plainText); // 寫入并加密數據}encrypted = msEncrypt.ToArray(); // 獲取加密后的字節數組}}}return encrypted; // 返回加密字節數組}static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV){// 參數檢查if (cipherText == null || cipherText.Length <= 0)throw new ArgumentNullException(nameof(cipherText));if (Key == null || Key.Length <= 0)throw new ArgumentNullException(nameof(Key));if (IV == null || IV.Length <= 0)throw new ArgumentNullException(nameof(IV));string plaintext = null;// 使用AES算法using (Aes aesAlg = Aes.Create()){aesAlg.Key = Key; // 解密密鑰aesAlg.IV = IV; // 初始化向量// 創建解密器ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);// 用內存流進行解密using (MemoryStream msDecrypt = new MemoryStream(cipherText)){// 創建解密流using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)){using (StreamReader srDecrypt = new StreamReader(csDecrypt)){plaintext = srDecrypt.ReadToEnd(); // 讀取并解密數據}}}}return plaintext; // 返回解密后的字符串}
}
非對稱加密示例:RSA
using System;
using System.Security.Cryptography;
using System.Text;public class RsaEncryptionExample
{public static void Main(){// 創建RSA實例using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()){// 導出公鑰和私鑰string publicKey = rsa.ToXmlString(false); // 公鑰,不包含私鑰string privateKey = rsa.ToXmlString(true); // 私鑰,包含全部信息string original = "Data for RSA encryption";// 加密數據byte[] encrypted = Encrypt(original, publicKey);// 解密數據string decrypted = Decrypt(encrypted, privateKey);Console.WriteLine($"Original: {original}");Console.WriteLine($"Decrypted: {decrypted}");}}public static byte[] Encrypt(string data, string publicKey){using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()){rsa.FromXmlString(publicKey); // 加載公鑰var dataBytes = Encoding.UTF8.GetBytes(data); // 轉換數據為字節數組return rsa.Encrypt(dataBytes, false); // 執行加密}}public static string Decrypt(byte[] data, string privateKey){using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()){rsa.FromXmlString(privateKey); // 加載私鑰var decryptedBytes = rsa.Decrypt(data, false); // 執行解密return Encoding.UTF8.GetString(decryptedBytes); // 轉換回字符串}}
}
SHA-256 散列示例
using System;
using System.Security.Cryptography;
using System.Text;public class HashingExample
{public static void Main(){string data = "Data to hash";// 計算SHA-256散列值string hash = ComputeSha256Hash(data);Console.WriteLine($"Data: {data}");Console.WriteLine($"Hash: {hash}");}public static string ComputeSha256Hash(string rawData){using (SHA256 sha256Hash = SHA256.Create()){// 將輸入字符串轉換為字節數組并計算其哈希值byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));// 將字節數組轉變為十六進制字符串StringBuilder builder = new StringBuilder();for (int i = 0; i < bytes.Length; i++){builder.Append(bytes[i].ToString("x2")); // 格式化為兩位十六進制}return builder.ToString(); // 返回散列值}}
}
- SHA-256散列值,通常用來驗證兩個文件是否相同。
這些示例展示了如何在C#中實現常見的安全和加密任務。如果有其他問題或需要進一步講解,請隨時告訴我!