Unity中 XML读写与加密

整体思路解析

数据存储和加密的主要逻辑思路:

使用XmlSerializer类对需要保存的数据类进行序列化操作,得到一串字符串。
将得到的字符串使用RijndaeManaged类和ICrytoTransform类进行加密操作,获得加密之后的字符串。
根据平台类型,确定文件保存的路径。
使用StreamWriter类将字符串保存到文件中。

数据加载和解密的主要逻辑思路:

根据存档文件的路径,使用StreamReader类读取文件中的内容(一串加密过的字符串)。
使用RijndaeManaged类和ICrytoTransform类对读取的文件内容进行解密操作,获得一串解密后的字符串。
使用XmlSerializer类对解密后的字符串进行反序列化操作,获得具体的游戏数据,并使用数据对游戏中的数据进行转换操作。

具体实现
首先创建XmlManager类,此类用来序列化与写入操作:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;

public class XmlManager {
    /// 
    /// 加密和解密秘钥
    /// 
    byte[] _keyArray = UTF8Encoding.UTF8.GetBytes("12348578902329367887724456789012");
    public bool HasFlie(string flieName)
    {
        return File.Exists(flieName);
    }
    /// 
    /// 创建XML
    /// 
    /// 
    /// 
    public void CreateXML(string flieName, String dataString)
    {
        StreamWriter writer;
        writer = File.CreateText(flieName);
        writer.Write(/*dataString*/Encrypt(dataString));
        writer.Close();
    }
    /// 
    /// 加载XML
    /// 
    /// 
    /// 
    public string LoadXML(string flieName)
    {
        StreamReader reader = File.OpenText(flieName);
        string dataString = reader.ReadToEnd();
        reader.Close();
        return /*dataString*/Decrypt(dataString);
    }

    #region 序列化/反序列化
    /// 
    /// 序列化
    /// 
    /// 
    /// 
    /// 
    public String SerializedObject(object pObject, System.Type ty)
    {
        MemoryStream mStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(ty);
        XmlTextWriter xmlTextWriter = new XmlTextWriter(mStream, Encoding.UTF8);
        xs.Serialize(xmlTextWriter, pObject);
        mStream = (MemoryStream)xmlTextWriter.BaseStream;
        return UTF8ByteArrayToString(mStream.ToArray());
    }
    /// 
    /// 反序列化
    /// 
    /// 
    /// 
    /// 
    public object DeserializedObject(string serializedString, System.Type ty)
    {
        XmlSerializer xs = new XmlSerializer(ty);
        MemoryStream mStream = new MemoryStream(stringToUTF8ByteArray(serializedString));
        return xs.Deserialize(mStream);
    }

    public string UTF8ByteArrayToString(byte[] bytes)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        return encoding.GetString(bytes);
    }

    byte[] stringToUTF8ByteArray(string dataString)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        return encoding.GetBytes(dataString);
    }
    #endregion

    #region 使用ICryptTransform加密/解密
    /// 
    /// 使用ICryptTransform进行加密
    /// 
    /// 
    /// 
    public string Encrypt(string toEncrypt) {
        ICryptoTransform cTransform = GetRijndaelManaged().CreateEncryptor();
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
       
        return Convert.ToBase64String(resultArray,0,resultArray.Length);
    }
    /// 
    /// 使用ICryptTransform进行解密
    /// 
    /// 
    /// 
    public string Decrypt(string toDecrypt)
    {
        ICryptoTransform cTransform = GetRijndaelManaged().CreateDecryptor();
        byte[] toDecryptArray = Convert.FromBase64String(toDecrypt);
        byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
        return UTF8Encoding.UTF8.GetString(resultArray);
    }

    RijndaelManaged GetRijndaelManaged()
    {
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = _keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        return rDel;
    }
    #endregion
}

然后创建一个存储数据的类

public class DevicePrice
{
    //------------AVS110
    /// 
    /// 光电版
    /// 
    public string Price30529143 ;
    /// 
    /// 视频版
    /// 
    public string Price30527071 ;
    /// 
    /// 全配版
    /// 
    public string Price30527072 ;
    public DevicePrice()
    {
        Price30529143 = "46113";
        Price30527071 = "53100";
        Price30527072 = "72546";
    }
}

操作类DataManager:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DataManager : MonoBehaviour {
    #region 共有变量
    #endregion
    #region 私有变量
    string dataFileName = "Price.Xml";
    XmlManager xm = new XmlManager();
    private DevicePrice m_devicePrice;
    #endregion
    // Use this for initialization
    void Start () {
        m_devicePrice = new DevicePrice();
        LoadPrice();
    }
	
	// Update is called once per frame
	void Update () {}
    /// 
    /// 创建XML
    /// 默认保存在桌面
    /// 
    public void CreatXML()
    {
        string dataFilePath = GetDataPath() + "/" + dataFileName;
        string serializedDataString = xm.SerializedObject(m_devicePrice, typeof(DevicePrice));
        xm.CreateXML(dataFilePath, serializedDataString);
        string dataFilePath2 = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/" + dataFileName;
        xm.CreateXML(dataFilePath2, serializedDataString);
    }
    /// 
    /// 加载价格
    /// 
    public void LoadPrice()
    {
        string dataFilePath = GetDataPath() + "/" + dataFileName;
        if (xm.HasFlie(dataFilePath))
        {
            string dataString = xm.LoadXML(dataFilePath);
            DevicePrice devicePriceFromXML = xm.DeserializedObject(dataString, typeof(DevicePrice)) as DevicePrice;
            if (devicePriceFromXML != null)
            {
                m_devicePrice = devicePriceFromXML;
            }               
            else
                Debug.Log("devicePriceFromXML is null");
        }
    }
    string GetDataPath()
    {
        //return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        return Application.dataPath;
        //return Application.streamingAssetsPath+"/Data";
    }
}

加密前:



-

46113

53100

72546


加密后:

yE2bP3gBwnYjvtvqcvbpudOi7MjZVP/kRwAnpo9njVqErh8dOdbUn4TthAl7rFRsTp9DPY54WOP2/IubyL9hNskqmnO/V4Ru69kVjDlkSkmNLYKF4VuX/Xl+MoKjfVHb7eZH+St724bx5q6e/QAv3LgOnAYX19YGsmfV24ANgLXqilKpE0potMRdhHFr0cF2dKpY6tFMyqJZAkR38RGkdueD4Hq8eOILxzTXK5LODel2KnmP9tqoXIBLPT1zN0nQ2iOMdZU+AcXPfpUdXjZ6s5qaWQj7qDUt9jC9+69VZmqo+1onSaRbRS4RuaZ4MIr942VHMM6rGdXdjUAViEfTO0QIi+GsN/90/3t7AzN8lZaU1CUT1ePqVYbq7Hv8TvN+fmIa3GL+PEB0e6qXoDC9DqAAx8sRQmFZgf509/hQRQCLlmBo9geFmROG2ENi2I/nAtSGD6tvjbMnbCtGle8jw5UqoZqMRHBeHHZbEK19vgqju3aEMBkGkA2l46q+OPfcoXurv3QhffD5l2dYIe3X20JOQiV/Vrf4vykRJ+CLo4mxG3BZf9oPS7bZE+etd/jOazonE+lNoZFi3G2vVkHrMZNxJZdxy592bpJEUuQL7x8AsBfbXqsy4ksSt05ax4o3ZhcN+sLNFVJt4Nt8VHRSmEp1LzF0NBdR7o3hoyroUhpzo+99a27XHfY7ivwRCZYOxMXewHa1/4vZ1pGdBasfKaB7BhUjHfKsM6hOM9zXKZ9fJBKfx+SRcOoKOeBqjIBhI1FJOmYixds7afadep2iwM9i/0ObPQ7n6KGuCwbhbDW2xg8AeJsMDYUdXOt7W28exKHFFSI6gdSl3LUsX6EqOrXzZ13qD5QgSWGZAIpP9hR4Y0WkBI0SApXW+gMx/G1+UtUZYnG/umviA4uDKJOPIvEfMdDbrtct4N7bjvbXhTV563tljgzrm9p2zW41K/lGymPr2eAd+ZCvRQcE6kU8Yv2C8irfGMpv

你可能感兴趣的:(xml,unity,c#)