作者: wtujoxk
查看: 2995|回复: 4
打印 上一主题 下一主题

【加密序列化】RSA 加密数据 XML序列化和反序列化

[复制链接]
跳转到指定楼层
楼主
wtujoxk 发表于 2016-11-28 09:47:35 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
查看: 2995|回复: 4
本帖最后由 wtujoxk 于 2016-11-28 09:51 编辑

说明:
DES AES加密数据,XML的序列化和反序列化,会在Debug下保存Test.xml文件

效果:



代码:

[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()
    {
    }
}



附件:
RSA XML_Serialize.rar (36.83 KB, 下载次数: 37)
RsaKeys.rar (4.38 KB, 下载次数: 45)


评分

参与人数 1金钱 +3 收起 理由
乔克斯 + 3 感谢LZ对论坛做出的贡献~

查看全部评分

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏3 转播转播
回复 论坛版权

使用道具 举报

沙发
xpsnail 发表于 2016-12-6 17:04:59 | 只看该作者
学习下,谢谢分享,,,,,,,,,,
板凳
772634508 发表于 2016-12-22 19:46:42 | 只看该作者
厉害了..............
回复

使用道具 举报

地板
772634508 发表于 2017-1-2 20:36:56 | 只看该作者
牛b的楼主
回复

使用道具 举报

5#
214679 发表于 2018-10-10 09:12:06 | 只看该作者
學習學習,謝謝分享!!
您需要登录后才可以回帖 登录 | 加入CSkin博客

本版积分规则

QQ|申请友链|小黑屋|手机版|Archiver|CSkin ( 粤ICP备13070794号

Powered by Discuz! X3.2  © 2001-2013 Comsenz Inc.  Designed by ARTERY.cn
GMT+8, 2024-11-25 09:20, Processed in 0.622996 second(s), 33 queries , Gzip On.

快速回复 返回顶部 返回列表