RijndaelManaged breaks excel files

103 Views Asked by At

Right, so... issue is as follows.

Excel (xlsx) gets uploaded, encrypted and saved to storage.

Later, same file gets read from storage, decrypted and downloaded.

BUT the downloaded file shows an error, regarding the xlsx file being potentially corrupted and prompts the user to try and fix it. When the user does that, the xlsx file does get fixed and opens successfully.

This was not really of much concern up till now, as we didn't use xlsx files all that much, but now we're using them and using the office preview app, which does not try and fix the files, so the preview app fails every single time. I checked the difference between the base64 of the stored file and the base64 of the read file, and it's indeed different - sometimes just a little different, sometimes quite a bit different.

Encryption/decryption code used is below.

P.S. Already tried removing padding by TrimEnd('\0'), that just messed up stuff even more and made the excel file unrecoverable.

    public static class BaseCrypter
    {
        private const string PassPhrase = "******************", Salt = "********";

        public static async Task<byte[]> EncryptBytes(byte[] inputBytes)
        {
            var RijndaelCipher = new RijndaelManaged { Mode = CipherMode.CBC };
            var salt = Encoding.ASCII.GetBytes(Salt);
            var password = new PasswordDeriveBytes(PassPhrase, salt, "SHA1", 2);

            var encrypter = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));

            var memoryStream = new MemoryStream();
            var cryptoStream = new CryptoStream(memoryStream, encrypter, CryptoStreamMode.Write);
            await cryptoStream.WriteAsync(inputBytes, 0, inputBytes.Length);
            cryptoStream.FlushFinalBlock();
            var CipherBytes = memoryStream.ToArray();

            memoryStream.Close();
            cryptoStream.Close();

            return CipherBytes;
        }

        public static async Task<byte[]> DecryptBytes(byte[] encryptedBytes)
        {
            var RijndaelCipher = new RijndaelManaged { Mode = CipherMode.CBC };
            var salt = Encoding.ASCII.GetBytes(Salt);
            var password = new PasswordDeriveBytes(PassPhrase, salt, "SHA1", 2);

            var Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));

            var memoryStream = new MemoryStream(encryptedBytes);
            var cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
            var plainBytes = new byte[encryptedBytes.Length];

            var count = await cryptoStream.ReadAsync(plainBytes, 0, plainBytes.Length);

            memoryStream.Close();
            cryptoStream.Close();

            return plainBytes;
        }
    }
0

There are 0 best solutions below