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


C#和JAVA的RSA密钥、公钥转换

C#的秘钥跟JAVA的密钥区别 RSA对于程序本身是没有区别的,其格式都是相同的。对于不同的程序来说,存储使用的语法(包装的类)会有所不同。 RSA语法和语法标准有很多,大的类型大概分为ASN.1、P...

PlayerPrefs类进行扩展加密存储整理

首先感谢三位大神的博客 : http://blog.csdn.net/u013895270/article/details/45579033 http://www.cnblogs.com/sunx...

unity3d中加密保存本地存档

unity中提供了PlayerPrefs来存储和读取本地的存档,根据unity的文档显示,很容易就能找到这些信息存储的位置 而且是明文的,很容易就看懂了 也可以修改,如何避免这种情况了,不如就加密一...

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

using UnityEngine; using System.Collections.Generic; using System.IO; using System.Security.Cryptogr...

Java反序列化漏洞通用利用分析

 1 背景 2015年11月6日,FoxGlove Security安全团队的@breenmachine 发布的一篇博客[3]中介绍了如何利用Java反序列化漏洞,来攻击最新版的WebLogi...

Java反序列化漏洞通用利用分析

原文出处: https://blog.chaitin.cn/2015-11-11_java_unserialize_rce/#h4.1_利用过程概述1 背景2015年11月6日,FoxGlove S...

反序列化作用

  • 2013年07月04日 07:12
  • 104KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Unity RSA 加密数据 序列化和反序列化 通用方法
举报原因:
原因补充:

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