当前位置: 欣欣网 > 码农

使用C#实现AES加密和解密JSON数据的实例

2024-03-04码农

以下是一个使用C#实现AES加密和解密JSON数据的例子:

  • ```csharpusing 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的安全存储和管理,以及处理加密和解密操作的错误和异常情况。