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

本文介绍了如何使用C#的AesEncryption类对.NET中的对象进行AES加密和解密,以JSON格式存储和传输,以及使用的相关技术和工具如JavaScriptSerializer和Base64编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;using System.Security.Cryptography;using System.Text;using System.Web.Script.Serialization;

namespace AesEncryptionExample{ public static class AesEncryption { public static string EncryptJson(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; } }

 public static 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 class Person { public string Name { get; set; } public int Age { get; set; } }  public class Program { public static void Main(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); } }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值