在C#中,有多種文本加密方法可供選擇。以下是一些常見的加密方法:
在選擇加密方法時,需要考慮數據的敏感性、系統的性能要求以及現有的安全標準等因素。同時,也需要注意保護密鑰的安全,因為密鑰的泄露會導致加密數據的泄露。
以下是一個使用AES加密方法的示例代碼:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string plaintext = "Hello, World!";
string key = "abcdefghijklmnop"; // 16字節密鑰
string iv = "1234567890abcdef"; // 16字節初始化向量
byte[] encrypted = Encrypt(plaintext, key, iv);
Console.WriteLine("Encrypted text: " + Convert.ToBase64String(encrypted));
string decrypted = Decrypt(encrypted, key, iv);
Console.WriteLine("Decrypted text: " + decrypted);
}
static byte[] Encrypt(string plaintext, string key, string iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(plaintext);
}
encrypted = memoryStream.ToArray();
}
}
}
return encrypted;
}
static string Decrypt(byte[] ciphertext, string key, string iv)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream(ciphertext))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader(cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
}
}
請注意,以上示例代碼僅用于演示目的,實際應用中可能需要考慮更多的安全因素,例如密鑰管理和錯誤處理等。