From be0a456067cdfbeabe5855bddf949d67603472a2 Mon Sep 17 00:00:00 2001 From: Kurt Date: Fri, 17 Apr 2020 14:00:34 -0700 Subject: [PATCH] Decrypt savefile in-place (less allocation) Each player and main.dat is ~11MB of allocation to read; old would read & decrypt into separate array = 22MB * (1 + playerCount). Cutting this in half reduces the amount of allocation and keeps stuff off gen2 LOH --- NHSE.Core/Encryption/Encryption.cs | 9 +++------ NHSE.Core/Save/Meta/EncryptedFilePair.cs | 8 ++++---- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/NHSE.Core/Encryption/Encryption.cs b/NHSE.Core/Encryption/Encryption.cs index 9efd23d..4537c09 100644 --- a/NHSE.Core/Encryption/Encryption.cs +++ b/NHSE.Core/Encryption/Encryption.cs @@ -21,12 +21,11 @@ private static byte[] GetParam(uint[] data, in int index) } /// - /// Decrypts the using the . + /// Decrypts the using the in place. /// /// Header Data /// Encrypted SaveData - /// Decrypted SaveData - public static byte[] Decrypt(byte[] headerData, byte[] encData) + public static void Decrypt(byte[] headerData, byte[] encData) { // First 256 bytes go unused var importantData = new uint[0x80]; @@ -41,10 +40,8 @@ public static byte[] Decrypt(byte[] headerData, byte[] encData) // Do the AES using var aesCtr = new Aes128CounterMode(counter); var transform = aesCtr.CreateDecryptor(key, counter); - var decData = new byte[encData.Length]; - transform.TransformBlock(encData, 0, encData.Length, decData, 0); - return decData; + transform.TransformBlock(encData, 0, encData.Length, encData, 0); } private static CryptoFile GenerateHeaderFile(uint seed, byte[] versionData) diff --git a/NHSE.Core/Save/Meta/EncryptedFilePair.cs b/NHSE.Core/Save/Meta/EncryptedFilePair.cs index d4338a5..b851131 100644 --- a/NHSE.Core/Save/Meta/EncryptedFilePair.cs +++ b/NHSE.Core/Save/Meta/EncryptedFilePair.cs @@ -29,10 +29,10 @@ protected EncryptedFilePair(string folder, string name) var hd = File.ReadAllBytes(hdr); var md = File.ReadAllBytes(dat); - var decrypted = Encryption.Decrypt(hd, md); + Encryption.Decrypt(hd, md); Header = hd; - Data = decrypted; + Data = md; DataPath = dat; HeaderPath = hdr; @@ -76,7 +76,7 @@ public IEnumerable InvalidHashes() } } - public string GetString(int offset, int maxLength) => StringUtil.GetString(Data, offset, maxLength); - public static byte[] GetBytes(string value, int maxLength) => StringUtil.GetBytes(value, maxLength); + protected string GetString(int offset, int maxLength) => StringUtil.GetString(Data, offset, maxLength); + protected static byte[] GetBytes(string value, int maxLength) => StringUtil.GetBytes(value, maxLength); } } \ No newline at end of file