Advertisement
EgonMilanVotrubec

FileStorage

Jun 19th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.77 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. /// Go to https://github.com/JamesNK/Newtonsoft.Json/releases and add the
  9. /// appropriate Newtonsoft.Json.dll to your Assets/Plugins folder.
  10. /// Alternatively, go to https://github.com/Votrubec/Newtonsoft.Json-AOT if you require
  11. /// an AOT version for platforms that don't suport JIT, such as IOS.
  12. using Newtonsoft.Json;
  13.  
  14. using UnityEngine;
  15.  
  16.  
  17. namespace Assets.Scripts
  18. {
  19.     public static class FileStorage
  20.     {
  21.         public static string SecurityKey { get; set; } = "Security Key For Encrypting JSON. Should Be Unique.";
  22.  
  23.         public static bool EncryptJSON { get; set; } = false;
  24.        
  25.         private static BinaryFormatter binaryFormatter;
  26.  
  27.  
  28.  
  29.         public static async Task<T> LoadAsync<T> ( string name ) where T : class
  30.         {
  31.             if ( binaryFormatter == null )
  32.                 binaryFormatter = new BinaryFormatter ( );
  33.  
  34.             var fileName = $"{Application.persistentDataPath}/{( uint ) name.GetHashCode ( )}.dat";
  35.  
  36.             if ( !File.Exists ( fileName ) )
  37.             {
  38. #if DEBUG
  39.                 Debug.LogWarning ( $"Load<{typeof ( T ).Name}> ( \"{name}\" ) File Not Found : {fileName}" );
  40. #endif
  41.                 return null;
  42.             }
  43. #if DEBUG
  44.             else
  45.                 Debug.Log ( $"Load<{typeof ( T ).Name}> ( \"{name}\" ) File Found : {fileName}" );
  46. #endif
  47.  
  48.             byte [ ] result;
  49.             int bytesRead = 0;
  50.             using ( FileStream file = File.Open ( fileName, FileMode.Open, FileAccess.Read, FileShare.None ) )
  51.             {
  52.                 result = new byte [ file.Length ];
  53.                 bytesRead = await file.ReadAsync ( result, 0, ( int ) file.Length );
  54.             }
  55.  
  56.             if ( bytesRead == 0 )
  57.             {
  58. #if DEBUG
  59.                 Debug.LogWarning ( $"Load<{typeof ( T ).Name}> ( \"{name}\" ) 0 bytes read." );
  60. #endif
  61.                 return null;
  62.             }
  63.  
  64.             try
  65.             {
  66.                 if ( typeof ( T ).IsSerializable )
  67.                 {
  68. #if DEBUG
  69.                     Debug.Log ( $"Load<{typeof ( T ).Name}> IsSerializable." );
  70. #endif
  71.                     using ( MemoryStream stream = new MemoryStream ( result ) )
  72.                     {
  73.                         return ( T ) binaryFormatter.Deserialize ( stream );
  74.                     }
  75.                 }
  76.                 else
  77.                 {
  78. #if DEBUG
  79.                     Debug.Log ( $"Load<{typeof ( T ).Name}> IsSerializable is False." );
  80. #endif
  81.                     string json = EncryptJSON ? Decrypt ( result ) : Encoding.UTF8.GetString ( result );
  82.                     return ( T ) JsonConvert.DeserializeObject<T> ( json );
  83.                 }
  84.             }
  85.             catch ( Exception e )
  86.             {
  87. #if DEBUG
  88.                 Debug.Log ( $"Load<{typeof ( T ).Name}> Failed: {e.Message}" );
  89. #endif
  90.                 return null;
  91.             }
  92.         }
  93.  
  94.  
  95.  
  96.         public static async Task<bool> SaveAsync ( string name, object o )
  97.         {
  98.             if ( binaryFormatter == null )
  99.                 binaryFormatter = new BinaryFormatter ( );
  100.  
  101.             var fileName = $"{Application.persistentDataPath}/{( uint ) name.GetHashCode ( )}.dat";
  102. #if DEBUG
  103.             Debug.Log ( $"Saving : {fileName}" );
  104. #endif
  105.  
  106.             if ( string.IsNullOrEmpty ( name ) || o == null )
  107.             {
  108. #if DEBUG
  109.                 Debug.Log ( "name and/or object to save was null." );
  110. #endif
  111.                 return false;
  112.             }
  113.  
  114.             try
  115.             {
  116.                 using ( FileStream file = File.Open ( fileName, FileMode.Create ) )
  117.                 {
  118.                     // We check to see if the object is serialisable. If so, we use the BinaryFormatter,
  119.                     // otherwise we serialise to JSON and encrypt that.
  120.                     if ( o.GetType ( ).IsSerializable )
  121.                     {
  122.                         binaryFormatter.Serialize ( file, o );
  123. #if DEBUG
  124.                         Debug.Log ( $"Saved Binary File : {fileName}" );
  125. #endif
  126.                     }
  127.                     else
  128.                     {
  129.                         var json = JsonConvert.SerializeObject ( o, Formatting.None );
  130.                         byte [ ] bytes = EncryptJSON ? Encrypt ( json ) : Encoding.UTF8.GetBytes ( json );
  131.                         await file.WriteAsync ( bytes, 0, bytes.Length );
  132. #if DEBUG
  133.                         Debug.Log ( $"Saved JSON SerializeObject : {fileName}" );
  134. #endif
  135.                     }
  136.                 }
  137.                 return true;
  138.             }
  139.             catch ( Exception e )
  140.             {
  141. #if DEBUG
  142.                 Debug.LogError ( $"Save Error : {e.Message} {e.InnerException}" );
  143. #endif
  144.                 return false;
  145.             }
  146.         }
  147.  
  148.  
  149.  
  150.         public static byte [ ] Encrypt ( string data )
  151.         {
  152.             byte [ ] keyArray;
  153.             byte [ ] dataBytesArray = Encoding.UTF8.GetBytes ( data );
  154.  
  155.             keyArray = Encoding.UTF8.GetBytes ( SecurityKey );
  156.  
  157.             TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider
  158.             {
  159.                 Key = keyArray,
  160.                 Mode = CipherMode.ECB,
  161.                 Padding = PaddingMode.PKCS7
  162.             };
  163.  
  164.             ICryptoTransform encryptor = provider.CreateEncryptor ( );
  165.             try
  166.             {
  167.                 byte [ ] resultArray = encryptor.TransformFinalBlock ( dataBytesArray, 0, dataBytesArray.Length );
  168.                 provider.Clear ( );
  169.                 return resultArray;
  170.             }
  171.             catch ( Exception e )
  172.             {
  173. #if DEBUG
  174.                 Debug.LogError ( $"Encrypt() Exception : {e.Message}" );
  175. #endif
  176.                 return null;
  177.             }
  178.         }
  179.  
  180.  
  181.  
  182.         public static string Decrypt ( byte [ ] dataBytesArray )
  183.         {
  184.             byte [ ] keyArray;
  185.  
  186.             keyArray = Encoding.UTF8.GetBytes ( SecurityKey );
  187.  
  188.             TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider
  189.             {
  190.                 Key = keyArray,
  191.                 Mode = CipherMode.ECB,
  192.                 Padding = PaddingMode.PKCS7
  193.             };
  194.  
  195.             ICryptoTransform decryptor = provider.CreateDecryptor ( );
  196.             try
  197.             {
  198.                 byte [ ] resultArray = decryptor.TransformFinalBlock ( dataBytesArray, 0, dataBytesArray.Length );
  199.                 provider.Clear ( );
  200.                 return Encoding.UTF8.GetString ( resultArray );
  201.             }
  202.             catch ( Exception e )
  203.             {
  204. #if DEBUG
  205.                 Debug.LogError ( $"Decrypt() Exception : {e.Message}" );
  206. #endif
  207.                 return null;
  208.             }
  209.         }
  210.     }
  211. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement