在C#中使用對稱加密技術可以通過使用內置的加密算法類來實現。以下是一種在C#中使用對稱加密技術的示例:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string originalText = "Hello World!";
string key = "mysecretkey"; // 16 bytes key for AES encryption
byte[] encryptedData = Encrypt(originalText, key);
string decryptedText = Decrypt(encryptedData, key);
Console.WriteLine($"Original Text: {originalText}");
Console.WriteLine($"Encrypted Data: {Convert.ToBase64String(encryptedData)}");
Console.WriteLine($"Decrypted Text: {decryptedText}");
}
static byte[] Encrypt(string text, string key)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = new byte[16]; // 16 bytes Initialization Vector for AES encryption
using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
{
byte[] data = Encoding.UTF8.GetBytes(text);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
}
}
}
static string Decrypt(byte[] encryptedData, string key)
{
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = new byte[16]; // 16 bytes Initialization Vector for AES encryption
using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
{
using (MemoryStream ms = new MemoryStream(encryptedData))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
}
}
在上面的示例中,我們使用了AES對稱加密算法來加密和解密文本數據。首先,我們生成一個16字節的密鑰和初始化向量(IV),然后使用這些密鑰和IV來創建加密器和解密器。加密器和解密器將文本數據轉換為字節數組,并對其進行加密和解密。最后,我們將加密后的數據和解密后的文本打印出來。