以下是一個使用C#實作AES加密和解密JSON數據的例子:
```csharp
using System;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
namespaceAesEncryptionExample
{
publicstatic classAesEncryption
{
publicstaticstringEncryptJson(object data, byte[] key, byte[] iv)
{
// 將物件轉換為JSON字串
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(data);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
byte[] encryptedData;
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(json);
}
encryptedData = msEncrypt.ToArray();
}
}
// 將加密後的數據轉換為Base64字串
string encryptedJson = Convert.ToBase64String(encryptedData);
return encryptedJson;
}
}
publicstatic T DecryptJson<T>(string encryptedJson, byte[] key, byte[] iv)
{
byte[] encryptedData = Convert.FromBase64String(encryptedJson);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
string decryptedJson;
using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
decryptedJson = srDecrypt.ReadToEnd();
}
}
}
// 將解密後的JSON字串轉換為物件
JavaScriptSerializer serializer = new JavaScriptSerializer();
T decryptedData = serializer.Deserialize<T>(decryptedJson);
return decryptedData;
}
}
}
public classPerson
{
publicstring Name { get; set; }
publicint Age { get; set; }
}
public classProgram
{
publicstaticvoidMain(string[] args)
{
byte[] key = Encoding.UTF8.GetBytes("ThisIsASecretKey");
byte[] iv = Encoding.UTF8.GetBytes("ThisIsAnIV123456");
Person person = new Person
{
Name = "Alice",
Age = 25
};
string encryptedJson = AesEncryption.EncryptJson(person, key, iv);
Console.WriteLine("加密後的數據: " + encryptedJson);
Person decryptedPerson = AesEncryption.DecryptJson<Person>(encryptedJson, key, iv);
Console.WriteLine("解密後的數據: " + decryptedPerson.Name + ", " + decryptedPerson.Age);
}
}
}
```
在上面的例子中,我們定義了一個`AesEncryption`類,其中包含`EncryptJson`和`DecryptJson`方法,分別用於加密和解密JSON數據。在加密過程中,我們使用Aes演算法和指定的金鑰和IV來加密JSON字串。在解密過程中,我們使用相同的金鑰和IV來解密加密的數據,並將解密後的JSON字串轉換為物件。
這只是一個簡單的範例,實際使用時應註意金鑰和IV的安全儲存和管理,以及處理加密和解密操作的錯誤和異常情況。