[C#] 纯文本查看 复制代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;
namespace XML_Serialize
{
class Program
{
//公钥
private const string PublicRsaKey =
@"<RSAKeyValue><Modulus>zKNV1AEbvGrTQyuat8kDhx4Z7HBmRX38GLYlgF1MM0/FFnGyyEccMkMfZV3dcO62fFVRAmEhgsvjAHwiJEL6sae73p5w/mxfRowkqZPm/bJaSwj5C1Z8cYqNwzu9AD+t3WVFvloL6wuRMH8G56XDb6tL7Q34VV0+zjGILpBRM0k=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
//私钥
private const string PrivateRsaKey =
@"<RSAKeyValue><Modulus>zKNV1AEbvGrTQyuat8kDhx4Z7HBmRX38GLYlgF1MM0/FFnGyyEccMkMfZV3dcO62fFVRAmEhgsvjAHwiJEL6sae73p5w/mxfRowkqZPm/bJaSwj5C1Z8cYqNwzu9AD+t3WVFvloL6wuRMH8G56XDb6tL7Q34VV0+zjGILpBRM0k=</Modulus><Exponent>AQAB</Exponent><P>zOM8liykU3k3QUkXoLh6K++iEvCddVepn8f37ws3BTgO7ErH0o3B2Xbip+b5kP80Xv5kAAL3PVPy7KnCXZz8Iw==</P><Q>/7AoTIoGw9sIqUdNaSxOPEQLiN1Y+O9UTecoCJHIasHb6VizoptSYHAiX2g7mbFuUrjLPaAfLuqhIiecn1rDow==</Q><DP>cKCxm3Pq2SAXKcI+RNFkB2bxVywBwpFv4y+PsU4e7rWELoxlD+9xElPyAI5NvlErvtRksETxGDtfnI0tFTzItQ==</DP><DQ>hthdeHg2tyYV/EiZX8U5AXmVZ7nsyWRW3rrxFwvjWcIhe4AHRNOLb0bUKeLrw9Oabk/9B+QhbfnZvwyLAlO45w==</DQ><InverseQ>rOGwQPcRCGeKEqnL/isp+8+wyj8vQ2naxcemI8swK4FX4VUTl78ZTq/2Z+HfuEGIrosUJUCQ3lFWDr0K8ucDeg==</InverseQ><D>Czh7iMvkwvCSk/DMo34sqNiAMGQ7X10YmRxHsyGqf3fExUXHuU6Y37KpgovijAIy1F9zOS+tQDhAwrKLxrQ7fbAFKKOgBFi56YurjxSIKXbe5ivpvFQ9NhEobghavuCkq8yvZ36YZ5IIhCik1G8GKWIYA05sli5txkJIBtq8AWc=</D></RSAKeyValue>";
static void Main(string[] args)
{
List<Information> serList = new List<Information>();
string path = @"Test.xml";
//赋值
for (int i = 0; i < 5; i++)
{
serList.Add(new Information("名字" + i, 20 + i));
}
GeneralSerialize(serList, path, PublicRsaKey);
List<Information> serTest = GeneralDeserialize<List<Information>>(path, PrivateRsaKey);
//输出返回的值
foreach (var temp in serTest)
{
Console.WriteLine(temp.name);
Console.WriteLine(temp.age);
}
Console.ReadKey();
}
/// <summary>
/// 加密序列化
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="obj">要序列化的对象</param>
/// <param name="path">保存路径</param>
/// <param name="publicKey">公钥</param>
static void GeneralSerialize<T>(T obj, string path, string publicKey)
{
if (string.IsNullOrEmpty(path)) return;
string data = null; //最后要保存的数据
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //rsa类
rsa.FromXmlString(publicKey); //使用公钥加密
MemoryStream msMax = new MemoryStream();
MemoryStream msSub = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
xs.Serialize(msMax, obj); //序列化到内存
byte[] maxSize = msMax.GetBuffer();
msMax.Flush();
msMax.Position = 0; //如果没有,就不能Read
msMax.Read(maxSize, 0, maxSize.Length);
int maxLength = rsa.KeySize / 8 - 11; //加密块最大长度限制
//如果数据超出maxLength,就要切割数据进行加密
if (maxSize.Length <= maxLength)
{
data = Convert.ToBase64String(rsa.Encrypt(maxSize, true)); //加密
}
else
{
byte[] buffer = new byte[maxLength];
msMax.Flush();
msMax.Position = 0;
int blockSize = msMax.Read(buffer, 0, maxLength);
while (blockSize > 0)
{
byte[] toEncrypt = new byte[blockSize];
Array.Copy(buffer, 0, toEncrypt, 0, blockSize);
byte[] crypToGraph = rsa.Encrypt(toEncrypt, false);
msSub.Write(crypToGraph, 0, crypToGraph.Length);//加密
blockSize = msMax.Read(buffer, 0, maxLength);
}
data = Convert.ToBase64String(msSub.ToArray());
}
Stream fs = File.Create(path);
StreamWriter sw = new StreamWriter(fs);
sw.Write(data); //写入XML文本保存
sw.Close();
fs.Close();
msSub.Close();
msMax.Close();
rsa.Clear();
}
/// <summary>
/// 加密反序列化
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="path">保存路径</param>
/// <param name="privateKey">私钥</param>
/// <returns></returns>
static T GeneralDeserialize<T>(string path, string privateKey)
{
if (string.IsNullOrEmpty(path)) return default(T);
string data = null;
byte[] decData = null;
XmlSerializer xs = new XmlSerializer(typeof(T));
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(privateKey);//使用私钥解密
Stream fs = File.OpenRead(path);
StreamReader sr = new StreamReader(fs);
data = sr.ReadToEnd(); //读入数据
byte[] strTobyte = Convert.FromBase64String(data);
int maxSize = rsa.KeySize / 8; //解密块最大长度限制
MemoryStream msMax = new MemoryStream(strTobyte);
MemoryStream msSub = new MemoryStream();
//如果数据超出maxLength,就要切割数据进行解密
if (strTobyte.Length <= maxSize)
{
decData = rsa.Decrypt(strTobyte, false); //解密
}
else
{
byte[] buffer = new byte[maxSize];
int blockSize = msMax.Read(buffer, 0, maxSize);
while (blockSize > 0)
{
byte[] toDecrypt = new byte[blockSize];
Array.Copy(buffer, 0, toDecrypt, 0, blockSize);
byte[] plainText = rsa.Decrypt(toDecrypt, false);//解密
msSub.Write(plainText, 0, plainText.Length);
blockSize = msMax.Read(buffer, 0, maxSize);
}
decData = msSub.ToArray();
}
MemoryStream msDes = new MemoryStream(decData); //将要反序列化的数据写入内存
T retObj = (T)xs.Deserialize(msDes); //反序列化
rsa.Clear();
msDes.Close();
msMax.Close();
msSub.Close();
return retObj;
}
}
}
[XmlType("人员信息")]
public class Information
{
[XmlAttribute("名字")] public string name;
[XmlAttribute("年龄")] public int age;
public Information(string name, int age)
{
this.name = name;
this.age = age;
}
//必须要有
public Information()
{
}
}