public MemoryStream SaveToStream() { MemoryStream stream = null; string json = m_saveData.ToJSON(); //Compress the data using LZF compression byte[] compressed = null; using (MemoryStream compMemStream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(compMemStream, Encoding.UTF8)) { writer.Write(json); writer.Close(); compressed = CLZF2.Compress(compMemStream.ToArray()); } } if (compressed != null) { byte[] encrypted = AESEncryptor.Encrypt(m_cryptoKey, m_cryptoIV, compressed); if (encrypted != null) { stream = new MemoryStream(); //Write version and headers! byte[] version = SaveUtilities.SerializeVersion(HeaderVersion); stream.Write(version, 0, version.Length); byte[] header = SaveUtilities.SerializeHeader(m_modifiedTime, m_deviceName, SaveUtilities.CalculateMD5Hash(encrypted), encrypted.Length); stream.Write(header, 0, header.Length); //Write encrypted and compressed data to stream stream.Write(encrypted, 0, encrypted.Length); } } return(stream); }
public LoadState LoadFromStream(Stream stream) { LoadState state = LoadState.Corrupted; try { byte[] decompressed = null; byte[] contentBytes = null; bool versionOkay = false; //Check version first int headerVersion = SaveUtilities.DeserializeVersion(stream); if (headerVersion == -1) { state = LoadState.Corrupted; } else if (headerVersion < HeaderVersion) { stream = UpgradeFile(stream); if (stream != null) { versionOkay = true; } else { state = LoadState.Corrupted; } } else if (headerVersion > HeaderVersion) { state = LoadState.VersionMismatch; } else { versionOkay = true; } if (versionOkay) { if (IsValidFile(stream, ref contentBytes)) { byte[] decrypted = AESEncryptor.Decrypt(m_cryptoKey, m_cryptoIV, contentBytes); if (decrypted != null) { decompressed = CLZF2.Decompress(decrypted); } else { Debug.LogError("SaveData :: Decryption failed!"); state = LoadState.Corrupted; } } else { Debug.LogError("SaveData :: File Corrupted!"); state = LoadState.Corrupted; } } if (decompressed != null) { using (MemoryStream jsonMemoryStream = new MemoryStream(decompressed)) { using (StreamReader reader = new StreamReader(jsonMemoryStream)) { if (m_saveData.FromJSON(reader)) { state = LoadState.OK; } else { Debug.LogWarning("Trying to load invalid JSON file at path: " + m_savePath); state = LoadState.Corrupted; } } } } } catch (Exception e) { //TODO determine exception types and see if any are recoverable! Debug.LogWarning("Exception when parsing file from stream"); Debug.LogWarning(e); } return(state); }