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

原创 2017年07月04日 16:19:21

不对称加密方法

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


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Unity3d 使用 RSA和DES 加密网络数据包

在网络通讯中,如果数据不进行加密,那么这些数据都是透明的 。就相当于你去寄信,但是这封信居然没有用信封装起来,这样邮局的任何一个人都可以拿过来看信的内容,毫无安全性可言。

Unity使用RSA

说明: RSA加密算法是最常用的非对称加密算法,RSA是第一个比较完善的公开密钥算法,它既能用于加密,也能用于数字签名。RSA以它的三个发明者Ron Rivest, Adi Shamir, Leon...

Unity3d 使用 RSA和DES 加密网络数据包

在同事的指导下,明白了网络加密的缘由以及手法。在网络通讯中,如果数据不进行加密,那么这些数据都是透明的 。 就相当于你去寄信,但是这封信居然没有用信封装起来,这样邮局的任何一个人都可以拿过来看信的内...

unity使用Newtonsoft.json反序列化json ,读取你想要的信息

比如这段json {"status":"10000","ret_msg":"\u6210\u529f","data":[{"goods_id":"1",&qu...

Json反序列化实例源码

  • 2012-12-28 13:37
  • 934KB
  • 下载

修复weblogic的JAVA反序列化漏洞的多种方法

0x00 前言 目前oracle还没有在公开途径发布weblogic的JAVA反序列化漏洞的官方补丁,目前看到的修复方法无非两条: 使用SerialKiller替换进行序列化操作的Obje...

反序列化作用

  • 2013-07-04 07:12
  • 104KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)