Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading.Tasks;
- /// Go to https://github.com/JamesNK/Newtonsoft.Json/releases and add the
- /// appropriate Newtonsoft.Json.dll to your Assets/Plugins folder.
- /// Alternatively, go to https://github.com/Votrubec/Newtonsoft.Json-AOT if you require
- /// an AOT version for platforms that don't suport JIT, such as IOS.
- using Newtonsoft.Json;
- using UnityEngine;
- namespace Assets.Scripts
- {
- public static class FileStorage
- {
- public static string SecurityKey { get; set; } = "Security Key For Encrypting JSON. Should Be Unique.";
- public static bool EncryptJSON { get; set; } = false;
- private static BinaryFormatter binaryFormatter;
- public static async Task<T> LoadAsync<T> ( string name ) where T : class
- {
- if ( binaryFormatter == null )
- binaryFormatter = new BinaryFormatter ( );
- var fileName = $"{Application.persistentDataPath}/{( uint ) name.GetHashCode ( )}.dat";
- if ( !File.Exists ( fileName ) )
- {
- #if DEBUG
- Debug.LogWarning ( $"Load<{typeof ( T ).Name}> ( \"{name}\" ) File Not Found : {fileName}" );
- #endif
- return null;
- }
- #if DEBUG
- else
- Debug.Log ( $"Load<{typeof ( T ).Name}> ( \"{name}\" ) File Found : {fileName}" );
- #endif
- byte [ ] result;
- int bytesRead = 0;
- using ( FileStream file = File.Open ( fileName, FileMode.Open, FileAccess.Read, FileShare.None ) )
- {
- result = new byte [ file.Length ];
- bytesRead = await file.ReadAsync ( result, 0, ( int ) file.Length );
- }
- if ( bytesRead == 0 )
- {
- #if DEBUG
- Debug.LogWarning ( $"Load<{typeof ( T ).Name}> ( \"{name}\" ) 0 bytes read." );
- #endif
- return null;
- }
- try
- {
- if ( typeof ( T ).IsSerializable )
- {
- #if DEBUG
- Debug.Log ( $"Load<{typeof ( T ).Name}> IsSerializable." );
- #endif
- using ( MemoryStream stream = new MemoryStream ( result ) )
- {
- return ( T ) binaryFormatter.Deserialize ( stream );
- }
- }
- else
- {
- #if DEBUG
- Debug.Log ( $"Load<{typeof ( T ).Name}> IsSerializable is False." );
- #endif
- string json = EncryptJSON ? Decrypt ( result ) : Encoding.UTF8.GetString ( result );
- return ( T ) JsonConvert.DeserializeObject<T> ( json );
- }
- }
- catch ( Exception e )
- {
- #if DEBUG
- Debug.Log ( $"Load<{typeof ( T ).Name}> Failed: {e.Message}" );
- #endif
- return null;
- }
- }
- public static async Task<bool> SaveAsync ( string name, object o )
- {
- if ( binaryFormatter == null )
- binaryFormatter = new BinaryFormatter ( );
- var fileName = $"{Application.persistentDataPath}/{( uint ) name.GetHashCode ( )}.dat";
- #if DEBUG
- Debug.Log ( $"Saving : {fileName}" );
- #endif
- if ( string.IsNullOrEmpty ( name ) || o == null )
- {
- #if DEBUG
- Debug.Log ( "name and/or object to save was null." );
- #endif
- return false;
- }
- try
- {
- using ( FileStream file = File.Open ( fileName, FileMode.Create ) )
- {
- // We check to see if the object is serialisable. If so, we use the BinaryFormatter,
- // otherwise we serialise to JSON and encrypt that.
- if ( o.GetType ( ).IsSerializable )
- {
- binaryFormatter.Serialize ( file, o );
- #if DEBUG
- Debug.Log ( $"Saved Binary File : {fileName}" );
- #endif
- }
- else
- {
- var json = JsonConvert.SerializeObject ( o, Formatting.None );
- byte [ ] bytes = EncryptJSON ? Encrypt ( json ) : Encoding.UTF8.GetBytes ( json );
- await file.WriteAsync ( bytes, 0, bytes.Length );
- #if DEBUG
- Debug.Log ( $"Saved JSON SerializeObject : {fileName}" );
- #endif
- }
- }
- return true;
- }
- catch ( Exception e )
- {
- #if DEBUG
- Debug.LogError ( $"Save Error : {e.Message} {e.InnerException}" );
- #endif
- return false;
- }
- }
- public static byte [ ] Encrypt ( string data )
- {
- byte [ ] keyArray;
- byte [ ] dataBytesArray = Encoding.UTF8.GetBytes ( data );
- keyArray = Encoding.UTF8.GetBytes ( SecurityKey );
- TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider
- {
- Key = keyArray,
- Mode = CipherMode.ECB,
- Padding = PaddingMode.PKCS7
- };
- ICryptoTransform encryptor = provider.CreateEncryptor ( );
- try
- {
- byte [ ] resultArray = encryptor.TransformFinalBlock ( dataBytesArray, 0, dataBytesArray.Length );
- provider.Clear ( );
- return resultArray;
- }
- catch ( Exception e )
- {
- #if DEBUG
- Debug.LogError ( $"Encrypt() Exception : {e.Message}" );
- #endif
- return null;
- }
- }
- public static string Decrypt ( byte [ ] dataBytesArray )
- {
- byte [ ] keyArray;
- keyArray = Encoding.UTF8.GetBytes ( SecurityKey );
- TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider
- {
- Key = keyArray,
- Mode = CipherMode.ECB,
- Padding = PaddingMode.PKCS7
- };
- ICryptoTransform decryptor = provider.CreateDecryptor ( );
- try
- {
- byte [ ] resultArray = decryptor.TransformFinalBlock ( dataBytesArray, 0, dataBytesArray.Length );
- provider.Clear ( );
- return Encoding.UTF8.GetString ( resultArray );
- }
- catch ( Exception e )
- {
- #if DEBUG
- Debug.LogError ( $"Decrypt() Exception : {e.Message}" );
- #endif
- return null;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement