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

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

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

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

效果:



代码:

[C#] 纯文本查看 复制代码
[/color][/size][/b]
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
    { 
        //keyVal输入32位,ivVal为16位
        static string keyVal = "qsedcvfrgthjuiklopoiuytrfgbvcdew";
        static string ivVal = "124578963axswedr";
        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, keyVal, ivVal);
            //XMLSerialize(serList, path);
            //List<Information> serTest = XMLDeserialize<List<Information>>(path);
            List<Information> serTest = GeneralDeserialize<List<Information>>(path, keyVal, ivVal);
            //输出返回的值
            foreach (var temp in serTest)
            {
                Console.WriteLine(temp.name);
                Console.WriteLine(temp.age);
            }
            Console.ReadKey();
        }
        /// <summary>  
        /// 加密序列化  
        /// </summary>  
        /// <param name="obj">要序列化的对象</param>  
        /// <param name="path">保存路径</param>  
        /// <param name="key">密钥值</param>  
        /// <param name="iv">加密辅助向量</param> 
        /// <returns></returns>  
        static void GeneralSerialize<T>(T obj, string path, string key, string iv)
        {
            if (string.IsNullOrEmpty(path)) return;
            //32位
            key = "qwertyuiopasdfghqwertyuiopasdfgh";
            //16位
            iv = "qwertyuiopasdfgh";
            using (var fileStream = File.Create(path))
            {
                //AES加密
                Rijndael aes = Rijndael.Create();
                aes.Key = Encoding.UTF8.GetBytes(ivVal.Length >= 32 ? ivVal.Substring(0, 32) : key);
                aes.IV = Encoding.UTF8.GetBytes(ivVal.Length >= 16 ? ivVal.Substring(0, 16) : iv);
                //DES加密
                //DESCryptoServiceProvider des = new DESCryptoServiceProvider()
                //{
                //    Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : key.Substring(0, 8)),
                //    IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : iv.Substring(0, 8))
                //};
                //加密流,如果是AES加密aes.CreateEncryptor(),DES加密des.CreateEncryptor()
                CryptoStream crStream = new CryptoStream(fileStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
                XmlSerializer xs = new XmlSerializer(typeof(T));
                xs.Serialize(crStream, obj);
                aes.Clear();
                crStream.Close();
                fileStream.Close();
            }
        }
        /// <summary>  
        /// 加密反序列化  
        /// </summary>  
        /// <param name="path">路径</param>  
        /// <param name="key">密钥值</param>  
        /// <param name="iv">加密辅助向量</param> 
        /// <returns></returns>  
        static T GeneralDeserialize<T>(string path, string key, string iv)
        {
            if (string.IsNullOrEmpty(path)) return default(T);
            //32位
            key = "qwertyuiopasdfghqwertyuiopasdfgh";
            //16位
            iv = "qwertyuiopasdfgh";
            using (var fileStream = File.OpenRead(path))
            {
                //AES加密
                Rijndael aes = Rijndael.Create();
                aes.Key = Encoding.UTF8.GetBytes(ivVal.Length >= 32 ? ivVal.Substring(0, 32) : key);
                aes.IV = Encoding.UTF8.GetBytes(ivVal.Length >= 16 ? ivVal.Substring(0, 16) : iv);
                //DES加密
                //DESCryptoServiceProvider des = new DESCryptoServiceProvider()
                //{
                //    Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : key.Substring(0, 8)),
                //    IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : iv.Substring(0, 8))
                //};
                //加密流,如果是AES加密aes.CreateEncryptor(),DES加密des.CreateEncryptor()
                CryptoStream crStream = new CryptoStream(fileStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
                XmlSerializer xs = new XmlSerializer(typeof(T));
                T retObj = (T)xs.Deserialize(crStream);
                aes.Clear();
                crStream.Close();
                fileStream.Close();
                return retObj;
            }
        }

        //未加密序列化
        static void XMLSerialize<T>(T obj, string path)
        {
            if (string.IsNullOrEmpty(path)) return;
            XmlSerializer xs = new XmlSerializer(typeof(T));
            Stream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
            xs.Serialize(fs, obj);
            fs.Flush();
            fs.Close();
            fs.Dispose();
        }
        //未加密反序列化
        static T XMLDeserialize<T>(string path)
        {
            if (string.IsNullOrEmpty(path)) return default(T);
            XmlSerializer xs = new XmlSerializer(typeof(T));
            Stream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            T serTest = (T)xs.Deserialize(fs);
            fs.Flush();
            fs.Close();
            fs.Dispose();
            return serTest;
        }
    }
}
[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()
    {
    }
}

[b][size=4][color=#ff0000]


附件:

DES AES XML_Serialize.rar (33.29 KB, 下载次数: 37)




评分

参与人数 1金钱 +3 收起 理由
乔克斯 + 3 感谢分享,LZ辛苦了~

查看全部评分

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

使用道具 举报

沙发
214679 发表于 2018-10-10 09:13:57 | 只看该作者
學習學習, 感谢分享!!
您需要登录后才可以回帖 登录 | 加入CSkin博客

本版积分规则

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

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

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