I utilized the Code Analysis tool, which provided the following warning.
Severity Code Description Project File Line Suppression State Warning CA2202 Object 'stream' can be disposed more than once in method 'Cipher.Encryptor(string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 43 Service Layer ...\Cipher.cs 43 Active
It stems from the "tower of power":
public static string Encryptor(string input)
{
var content = String.Empty;
var cipher = new RijndaelManaged();
var plain = Encoding.Unicode.GetBytes(input);
var key = new PasswordDeriveBytes(password, salt);
using (var encrypt = cipher.CreateEncryptor(key.GetBytes(32), key.GetBytes(16)))
using (var stream = new MemoryStream())
using (var cryptographic = new CryptoStream(stream, encrypt, CryptoStreamMode.Write))
{
cryptographic.Write(plain, 0, plain.Length);
cryptographic.FlushFinalBlock();
content = Convert.ToBase64String(stream.ToArray());
}
return content;
}
In this instance I'm utilizing a MemoryStream
, CryptoStream
, and ICryptoTransform
. Why does Visual Studio's Code Analysis flag this for a warning? This is from the built in Code Analysis in Visual Studio 2015.
=================
Here's a shorter repro:
using System.IO;
using System.Security.Cryptography;
namespace ClassLibrary1
{
public class Class1
{
void foo()
{
using (var memStream = new MemoryStream())
using (var xForm = new FromBase64Transform())
using (var cStream = new CryptoStream(memStream, xForm, CryptoStreamMode.Read))
;
}
}
}
... and this can be seen in VS2013 Up5