はCA2000と苦情がありません:スコープ(https://msdn.microsoft.com/library/ms182289.aspx)を失う前にオブジェクトを配置する。これのコードでは、次の警告.NETコード解析警告
警告CA2000を生成メソッド 'CryptoComputer.Encrypt(string、string、string、string)'、オブジェクト 'new RijndaelManaged()'はすべての例外パスに沿って配置されません。 System.IDisposable.Disposeを呼び出す前にオブジェクト 'new RijndaelManaged()'をスコープから外してください。
public static string Encrypt(string plainText, string passPhrase, string saltValue, string initVector)
{
var initVectorBytes = Encoding.UTF8.GetBytes(initVector);
var saltValueBytes = Encoding.UTF8.GetBytes(saltValue);
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
string cipherText;
PasswordDeriveBytes password = null;
RijndaelManaged symmetricKey = null;
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize/8);
symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherTextBytes = memoryStream.ToArray();
cipherText = Convert.ToBase64String(cipherTextBytes);
}
catch (Exception)
{
throw;
}
finally
{
password?.Dispose();
symmetricKey?.Dispose();
memoryStream?.Dispose();
}
return cipherText;
}
どのように私は
使用 "を使用して(...)"、symmetricKey、MemoryStreamを。 –
Microsoftの分析ルールで「password?Dispose()」という構文が認識されないためですか? 'if(obj!= null)obj.Dispose();'として書き直すとどうなりますか? – kennyzx
Kennyzxはおそらく正しいでしょう...古い方法でコードを書いたり、偽の警告を抑えなければならないでしょう –