[ 유니티3D엔진 ] XML Serialize Encrypt/Decrypt.
1. Encrypt
//-----------------------------------------------------------------------------
public static void SerializeEncryptObject(string path, object obj, System.Type type, SymmetricAlgorithm key)
{
using(FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
using(CryptoStream cs = new CryptoStream(fs, key.CreateEncryptor(), CryptoStreamMode.Write))
{
using(StreamWriter sw = new StreamWriter(cs, Encoding.UTF8))
{
try
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(sw, obj, ns);
}
catch (System.Exception ex)
{
Debug.LogWarning(ex.ToString());
}
finally
{
sw.Close();
cs.Close();
fs.Close();
}
}
}
}
}
2. Decrypt
//-----------------------------------------------------------------------------
public static string LoadXmlFromEncryptFile(string _filePath, SymmetricAlgorithm key)
{
if (File.Exists(_filePath) == false)
{
_deserializeErrorString = System.String.Format("File({0}) does not exists", _filePath);
return "";
}
using(FileStream fs = File.Open(_filePath, FileMode.Open))
{
using(CryptoStream cs = new CryptoStream(fs, key.CreateDecryptor(), CryptoStreamMode.Read))
{
using(StreamReader sr = new StreamReader(cs, Encoding.UTF8))
{
try
{
return sr.ReadToEnd();
}
catch(System.Exception ex)
{
Debug.LogWarning(ex.ToString());
_deserializeErrorString = ex.ToString();
}
finally
{
sr.Close();
cs.Close();
fs.Close();
}
}
}
}
return "";
}
3. Usage
-
private readonly string SECRET_KEY = "12345678"; // must be 64bit, 8bytes
-
private System.Security.Cryptography.DESCryptoServiceProvider mCryptoProvider = null;
-
mCryptoProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
mCryptoProvider.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(SECRET_KEY); mCryptoProvider.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(SECRET_KEY);
-
SerializeEncryptObject("FilePath", Type, mCryptoProvider);
string xmlString = LoadXmlFromEncryptFile("FilePath", mCryptoProvider);
http://limchaeng.tistory.com/21