At this point I'm quite confused about the implementation of an encryption/decryption of game data.
Write function
private void WriteEncryptedData<T>(T Data, string path)
{
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Convert.FromBase64String(KEY);
aes.IV = Convert.FromBase64String(IV);
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using MemoryStream memoryStream = new();
using CryptoStream cryptoStream = new(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Data)));
cryptoStream.FlushFinalBlock();
array = memoryStream.ToArray();
}
File.WriteAllText(path, Convert.ToBase64String(array));
}
And read function
private T ReadEncryptedData<T>(string path)
{
var data = File.ReadAllText(path);
byte[] array = Convert.FromBase64String(data);
string result;
using (Aes aes = Aes.Create())
{
aes.Key = Convert.FromBase64String(KEY);
aes.IV = Convert.FromBase64String(IV);
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform cryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV);
using MemoryStream decryptionStream = new(array);
using CryptoStream cryptoStream = new(
decryptionStream,
cryptoTransform,
CryptoStreamMode.Read
);
cryptoStream.Flush();
result = Encoding.UTF8.GetString(decryptionStream.ToArray());
}
Debug.Log($"Decrypted result (if the following is not legible, probably wrong key or iv): {result}");
return JsonConvert.DeserializeObject<T>(result);
}
For some reason I get the following error and at this point I'm worried that I'm missing something important in the implementation. I'm using hard-coded KEY and IV. I plan to generate the IV dynamically.
Failed to load data due to: Bad PKCS7 padding. Invalid length 0. at Mono.Security.Cryptography.SymmetricTransform.ThrowBadPaddingException (System.Security.Cryptography.PaddingMode padding, System.Int32 length, System.Int32 position) [0x00056] in <381999f96ea944d79e461a81dcbea654>:0 at Mono.Security.Cryptography.SymmetricTransform.FinalDecrypt (System.Byte[] inputBuffer, System.Int32 inputOffset, System.Int32 inputCount) [0x00146] in <381999f96ea944d79e461a81dcbea654>:0 at Mono.Security.Cryptography.SymmetricTransform.TransformFinalBlock (System.Byte[] inputBuffer, System.Int32 inputOffset, System.Int32 inputCount) [0x0002e] in <381999f96ea944d79e461a81dcbea654>:0 at System.Security.Cryptography.CryptoStream.FlushFinalBlock () [0x00013] in <381999f96ea944d79e461a81dcbea654>:0 at System.Security.Cryptography.CryptoStream.Dispose (System.Boolean disposing) [0x0000b] in <381999f96ea944d79e461a81dcbea654>:0 at System.IO.Stream.Close () [0x00000] in <381999f96ea944d79e461a81dcbea654>:0 at System.IO.Stream.Dispose () [0x00000] in <381999f96ea944d79e461a81dcbea654>:0