I have some code that decrypts a password with Rijndael
public static string DecryptPassword(string encrypted) {
using (MemoryStream ms = new MemoryStream())
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor(mGlobalKey, mGlobalVector))
using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read)) {
byte[] encryptedBytes = Convert.FromBase64String(encrypted);
cs.Write(encryptedBytes, 0, encryptedBytes.Length);
cs.FlushFinalBlock();
return Encoding.Unicode.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}
}
The problem is that disposing the cryptostream causes an exception
System.IndexOutOfRangeException : Index was outside the bounds of the array.
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.IO.Stream.Dispose()
I found some links to similar problems but no solutions.
Is it safe to just remove the Disposing of the cryptostream or will that just cause the finalizer to blow up at a later time?