Unity 讀寫加密讀寫xml
阿新 • • 發佈:2018-12-10
開發unity的過程中有不斷進行沙盒讀取操作,每次操作都需要進行一堆程式碼書寫,並且容易暴露資料,在這裡進行封裝一個類進行方便沙盒讀寫和進行加密
直接貼程式碼
/// <summary> /// ***作者:黛墨*** ///*** 時間:2018-9-16*** /// *** XmlManage*** /// </summary> using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using UnityEngine; using System.Text; using System.Security.Cryptography; using System; public class XmlManage { private string Path=null; public XmlNode Root = null; private XmlDocument Doc = null; public bool Encryption = false;//是否採用加密方式進行儲存 public string Key="123456789";//必須32位不是32位進行補充32位 private bool isone = false; public XmlManage(string path,string key=null) { #if UNITY_EDITOR||UNITY_STANDALONE_WIN||UNITY_IPHONE Path = Application.persistentDataPath + @"/"; #elif UNITY_ANDROID Path = "file://" + Application.persistentDataPath+ @"/"; #endif this.Path += path+".xml"; //查詢目錄 int index = this.Path.Length - 1; for (int i = this.Path.Length-1; i >=0; i--) { if (this.Path[i] == '/' || this.Path[i] == '\\') { index = i; break; } } StringBuilder pathstr = new StringBuilder(); for (int i = 0; i <=index; i++) { pathstr.Append(this.Path[i]); } if (!Directory.Exists(pathstr.ToString())) { Directory.CreateDirectory(pathstr.ToString()); } if (key != null) { Encryption = true;Key = key; } if (Encryption) { if (Key.Length < 32) { index = 0; while (Key.Length < 32) { Key += Key[index]; index++; } } else { if (Key.Length > 32) { StringBuilder str_ = new StringBuilder(); for (int i = 0; i < 32; i++) { str_.Append(key[i]); } Key = str_.ToString(); } } } Read(); } public void Read() { XmlDocument doc = new XmlDocument(); if (!File.Exists(Path)) { XmlElement newxmlele = doc.CreateElement("Root"); XmlAttribute xmlattri = doc.CreateAttribute("Type"); xmlattri.Value = "root"; newxmlele.SetAttributeNode(xmlattri); Root = newxmlele; doc.AppendChild(Root); Doc = doc; Sava(); isone = true; } else { //如果取樣加密方式進行其他方式讀取 if (Encryption) { doc.LoadXml(Decrypt(File.ReadAllText(Path))); } else doc.Load(Path); Root = doc.SelectSingleNode("Root"); } Doc = doc; } public bool IsCreate { get { return isone; } } public int GetInt(string name) { var node=GetNode(name); if (node == null) return 0; var type=node.Attributes["Type"]; if (type == null) return 0; if (type.Value == "Int") return int.Parse(node.InnerText); else return 0; } public void SetInt(string name,int value) { var node = GetNode(name); if (node == null) { var ele = Doc.CreateElement(name); ele.InnerText = value.ToString(); var att = Doc.CreateAttribute("Type"); att.Value = "Int"; ele.SetAttributeNode(att); Root.AppendChild(ele); } else if(node.Attributes[0].Value=="Int") node.InnerText = value.ToString(); } public float GetFloat(string name) { var node = GetNode(name); if (node == null) return 0; var type = node.Attributes["Type"]; if (type == null) return 0; if (type.Value == "Float") return float.Parse(node.InnerText); else return 0; } public void SetFloat(string name, float value) { var node = GetNode(name); if (node == null) { var ele = Doc.CreateElement(name); ele.InnerText = value.ToString("F5"); var att = Doc.CreateAttribute("Type"); att.Value = "Float"; ele.SetAttributeNode(att); Root.AppendChild(ele); } else if (node.Attributes[0].Value == "Float") node.InnerText = value.ToString("F5"); } public bool GetBool(string name) { var node = GetNode(name); if (node == null) return false; var type = node.Attributes["Type"]; if (type == null) return false; if (type.Value == "Bool") return bool.Parse(node.InnerText); else return false; } public void SetBool(string name, bool value) { var node = GetNode(name); if (node == null) { var ele = Doc.CreateElement(name); ele.InnerText = value.ToString(); var att = Doc.CreateAttribute("Type"); att.Value = "Bool"; ele.SetAttributeNode(att); Root.AppendChild(ele); } else if (node.Attributes[0].Value == "Bool") node.InnerText = value.ToString(); } public bool Exists(string name) { return Root.SelectNodes(name).Count > 0?true:false; } public XmlNode GetNode(string name) { var arr = Root.SelectNodes(name); return arr.Count > 0 ? arr[0] : null; } public void Sava() { //Debug.Log(ConvertXmlToString(Doc)); if (Encryption) { string str = ConvertXmlToString(Doc); File.WriteAllText(Path, Encrypt(str)); } else Doc.Save(Path); } public override string ToString() { return "XmlManage:"+ Path+Root.ToString()+":"+ ConvertXmlToString(Doc); } public void Delate() { if (File.Exists(Path)) { File.Delete(Path); } } private string Encrypt(string toE)//加密 { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toE); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } private string Decrypt(string toD)//解密 { //加密和解密採用相同的key,具體值自己填,但是必須為32位// byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] toEncryptArray=null; byte[] resultArray=null; try { toEncryptArray = Convert.FromBase64String(toD); resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); } catch (Exception) { throw new Exception("解密失敗核對密碼"); } return UTF8Encoding.UTF8.GetString(resultArray); } public string ConvertXmlToString(XmlDocument xmlDoc) { MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, null); writer.Formatting = Formatting.Indented; xmlDoc.Save(writer); StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8); stream.Position = 0; string xmlString = sr.ReadToEnd(); sr.Close(); stream.Close(); return xmlString; } }
以上程式碼不進行闡述我接下來貼出使用方法和效果