對稱加密雙方共用同組金鑰,金鑰管理與傳遞安全至關重要(通常對金鑰再加密傳輸)。

public static byte[] EncryptStringToBytes_AES(byte[] fileContentBytes, byte[] Key, byte[] IV)
{
if (fileContentBytes == null || fileContentBytes.Length <= 0) throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV");
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.PKCS7;
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))
{
csEncrypt.Write(fileContentBytes, 0, fileContentBytes.Length);
csEncrypt.FlushFinalBlock();
return msEncrypt.ToArray();
}
}
}
public static byte[] DecryptBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0) throw new ArgumentNullException("IV");
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.PKCS7;
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))
{
byte[] tempBuffer = new byte[cipherText.Length];
int totalBytesRead = csDecrypt.Read(tempBuffer, 0, tempBuffer.Length);
return tempBuffer.Take(totalBytesRead).ToArray();
}
}
}
private static void _EncryptAndDecrypt()
{
ASCIIEncoding asciiEnc = new ASCIIEncoding();
byte[] initVector = asciiEnc.GetBytes("16bytesInitVec!"); // 16 bytes IV
byte[] key = asciiEnc.GetBytes("16bytesSecretKey"); // 16 bytes Key (AES-128)
string original = "敏感資料內容";
byte[] encrypted = EncryptStringToBytes_AES(asciiEnc.GetBytes(original), key, initVector);
byte[] decrypted = DecryptBytes(encrypted, key, initVector);
Console.WriteLine(asciiEnc.GetString(decrypted)); // 輸出原文
}
實務上金鑰應透過非對稱加密或金鑰交換協定安全分發,IV 每次加密應隨機產生並與密文一同儲存。