在我的一些项目中,我一直在使用一对久经考验的数据加密/解密方法(加密方法粘贴在下面)。但是我一直被这个关于 memoryStream 对象的 CA2202 警告(“不要多次处理对象”)所困扰。我相信我以适当的方式处理了这个问题,但每当我在 Visual Studio 中运行分析时,我仍然会收到警告。它从未在生产代码中引发异常,但我仍然想一劳永逸地摆脱警告。那可能吗?还是我应该忽略它?提前致谢。
public static string Encrypt(string clearText, string passPhrase, string saltValue)
{
byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText);
byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);
Rfc2898DeriveBytes passPhraseDerviedBytes = new Rfc2898DeriveBytes(passPhrase, saltValueBytes);
byte[] keyBytes = passPhraseDerviedBytes.GetBytes(32);
byte[] initVectorBytes = passPhraseDerviedBytes.GetBytes(16);
RijndaelManaged symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC };
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
byte[] cipherTextBytes = null;
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(clearTextBytes, 0, clearTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
}
}
finally
{
if (memoryStream != null)
{
memoryStream.Dispose();
}
}
return Convert.ToBase64String(cipherTextBytes);
}