[c#] Padding is invalid and cannot be removed?

I came across this as a regression bug when refactoring code from traditional using blocks to the new C# 8.0 using declaration style, where the block ends when the variable falls out of scope at the end of the method.

Old style:

//...
using (MemoryStream ms = new MemoryStream())
{
    using (CryptoStream cs = new CryptoStream(ms, aesCrypto.CreateDecryptor(), CryptoStreamMode.Write))
    {
        cs.Write(rawCipherText, 0, rawCipherText.Length);
    }

    return Encoding.Unicode.GetString(ms.ToArray());
}

New, less indented style:

//...
using MemoryStream ms = new MemoryStream();
using CryptoStream cs = new CryptoStream(ms, aesCrypto.CreateDecryptor(), CryptoStreamMode.Write);

cs.Write(rawCipherText, 0, rawCipherText.Length);
cs.FlushFinalBlock();

return Encoding.Unicode.GetString(ms.ToArray());

With the old style, the using block for the CryptoStream terminated and the finalizer was called before memory stream gets read in the return statement, so the CryptoStream was automatically flushed.

With the new style, the memory stream is read before the CryptoStream finalizer gets called, so I had to manually call FlushFinalBlock() before reading from the memory stream in order to fix this issue. I had to manually flush the final block for both the encrypt and the decrypt methods, when they were written in the new using style.