0

我的加密代码是

{
    AesManaged aes = null;
    MemoryStream memoryStream = null;
    CryptoStream cryptoStream = null;

    try
    {
        Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), 10000);

        aes = new AesManaged();
        aes.Key = rfc2898.GetBytes(32);
        aes.IV = rfc2898.GetBytes(16);

        memoryStream = new MemoryStream();
        cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

        byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
        cryptoStream.Write(data, 0, data.Length);
        cryptoStream.FlushFinalBlock();

        return Convert.ToBase64String(memoryStream.ToArray());
    }
    finally
    {
        if (cryptoStream != null)
            cryptoStream.Close();

        if (memoryStream != null)
            memoryStream.Close();

        if (aes != null)
            aes.Clear();
    }
}

我刚刚尝试了代码分析,它给了我

CA2202
Do not dispose objects multiple times 
Object 'memoryStream' can be disposed more than once in method 'EncryptDecrypt.Encrypt(string, string, string)'. 
To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

但是我的代码运行良好我创建了 memoryStream 和 cryptoStream 并在之后关闭了它们......但我无法理解为什么它会多次告诉我多个对象

4

1 回答 1

1

两次处理同一个对象的状态准则IDisposable在第二次应该没有效果。

但是,并非所有实现都遵循此指南,因此代码分析告诉您不要依赖它。

在这方面,您的特定对象是安全的,因此您没有实际问题。

于 2013-09-17T13:31:36.630 回答