Unity RSA 加密数据 序列化和反序列化 通用方法

来源:互联网 发布:淘宝网店怎么改价格 编辑:程序博客网 时间:2024/06/02 03:59

不对称加密方法

using System;using UnityEngine;using System.Collections.Generic;using System.IO;using System.Security.Cryptography;using System.Xml.Serialization; ///@brief///文件名称:SerializeTest///功能描述:///数据表:///作者:YuXianQiang///日期:#CreateTime#///R1:///修改作者:///修改日期:///修改理由: public class RSAEncryptionDecrypt : MonoBehaviour{    //公钥    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>";     void Start()    {        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)        {            Debug.Log(temp.name);            Debug.Log(temp.age);        }    }     /// <summary>    /// 加密序列化      /// </summary>    /// <typeparam name="T">类型</typeparam>    /// <param name="obj">要序列化的对象</param>    /// <param name="path">保存路径</param>    /// <param name="publicKey">公钥</param>    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>    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() { }}


原创粉丝点击