使用加密资源尝试/捕获/最后

时间:2013-10-16 16:14:11

标签: c# asp.net .net encryption try-catch

我的网站上有以下代码。它将URL查询作为名为commandencrypted的字符串。我有一个try / catch / finally块,它将加密的命令复制到内存流,然后将其解密回字符串。如果try块中发生任何错误,则在catch块中处理它们。但是,我想确保在finally块中关闭所使用的所有资源。当提供无效的URL查询命令时,我在尝试关闭csencrypted命令CryptoStream时收到异常。例外细节遵循代码。

    // Resources used for storing and decrypting the encrypted client command
    MemoryStream msencryptedcommand = null;
    RijndaelManaged rmencryptedcommand = null;
    CryptoStream csencryptedcommand = null;
    StreamReader srdecryptedcommand = null;
    MemoryStream msdecryptedcommand = null;

    try
    {
        // Copy the encrypted client command (where two characters represent a byte) to a memorystream
        msencryptedcommand = new MemoryStream();
        for (int i = 0; i < encryptedcommand.Length; )
        {
            msencryptedcommand.WriteByte(Byte.Parse(encryptedcommand.Substring(i, 2), NumberStyles.HexNumber));
            i = i + 2;
        }
        msencryptedcommand.Flush();
        msencryptedcommand.Position = 0;

        // Define parameters used for decryption
        byte[] key = new byte[] { //bytes hidden// };
        byte[] iv = new byte[] { //bytes hidden// };
        rmencryptedcommand = new RijndaelManaged();
        csencryptedcommand = new CryptoStream(msencryptedcommand, rmencryptedcommand.CreateDecryptor(key, iv), CryptoStreamMode.Read);
        msdecryptedcommand = new MemoryStream();

        // Decrypt the client command
        int decrytptedbyte;
        while ((decrytptedbyte = csencryptedcommand.ReadByte()) != -1)
        {
            msdecryptedcommand.WriteByte((byte)decrytptedbyte);
        }

        // Store the decrypted client command as a string
        srdecryptedcommand = new StreamReader(msdecryptedcommand);
        srdecryptedcommand.BaseStream.Position = 0;
        string decryptedcommand = srdecryptedcommand.ReadToEnd();
    }
    catch (Exception ex)
    {
        ErrorResponse("Invalid URL Query", context, ex.ToString());
        return;
    }
    finally
    {
        // If any resources were used, close or clear them
        if (srdecryptedcommand != null)
        {
            srdecryptedcommand.Close();
        }

        if (msdecryptedcommand != null)
        {
            msdecryptedcommand.Close();
        }

        if (csencryptedcommand != null)
        {
            csencryptedcommand.Close();
        }

        if (rmencryptedcommand != null)
        {
            rmencryptedcommand.Clear();
        }

        if (msencryptedcommand != null)
        {
            msencryptedcommand.Close();
        }
    }
  

发生以下未处理的异常:System.Security.Cryptography.CryptographicException:要解密的数据的长度无效。在System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(字节[] INPUTBUFFER,的Int32 inputOffset,的Int32 inputCount)在System.Security.Cryptography.CryptoStream.FlushFinalBlock()在System.Security.Cryptography.CryptoStream.Dispose(布尔处置)在系统.IO.Stream.Close()在dongleupdate.ProcessRequest(HttpContext的上下文)中update.ashx:管线92以System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()在System.Web.HttpApplication。 ExecuteStep(IExecutionStep一步,布尔和放大器; completedSynchronously)网址推荐人:用户代理:Mozilla的/ 5.0(Windows NT的6.1; WOW64)为AppleWebKit / 537.36(KHTML,例如Gecko)Chrome浏览器/ Safari浏览器30.0.1599.69 / 537.36请求URL:?update.ashx AA

编辑:

我将代码更改为使用语句。这也是确保所有资源都关闭的有效方法吗?

    try
    {
        // Copy the encrypted client command (where two characters represent a byte) to a memorystream
        using (MemoryStream msencryptedcommand = new MemoryStream())
        {
            for (int i = 0; i < encryptedcommand.Length; )
            {
                msencryptedcommand.WriteByte(Byte.Parse(encryptedcommand.Substring(i, 2), NumberStyles.HexNumber));
                i = i + 2;
            }
            msencryptedcommand.Flush();
            msencryptedcommand.Position = 0;

            // Define parameters used for decryption
            byte[] key = new byte[] { //bytes hidden// };
            byte[] iv = new byte[] { //bytes hidden// };
            using (RijndaelManaged rmencryptedcommand = new RijndaelManaged())
            {
                using (CryptoStream csencryptedcommand = new CryptoStream(msencryptedcommand, rmencryptedcommand.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                {
                    using (MemoryStream msdecryptedcommand = new MemoryStream())
                    {

                        // Decrypt the client command
                        int decrytptedbyte;
                        while ((decrytptedbyte = csencryptedcommand.ReadByte()) != -1)
                        {
                            msdecryptedcommand.WriteByte((byte)decrytptedbyte);
                        }

                        // Store the decrypted client command as a string
                        using (StreamReader srdecryptedcommand = new StreamReader(msdecryptedcommand))
                        {
                            srdecryptedcommand.BaseStream.Position = 0;
                            string decryptedcommand = srdecryptedcommand.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        ErrorResponse("Invalid URL Query", context, ex.ToString());
        return;
    }

2 个答案:

答案 0 :(得分:5)

CryptoStream包裹在using区块中,然后它会自动关闭并通过Dispose Pattern为您处理,如下所示:

using(csencryptedcommand = new CryptoStream(msencryptedcommand, 
    rmencryptedcommand.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
    // Do things with crypto stream here
}

阅读using Statement (C# Reference)文档以获取更多信息。

更新:

使用Reflector,以下是CryptoStream Dispose方法的代码:

protected override void Dispose(bool disposing)
{
    try
    {
        if (disposing)
        {
            if (!this._finalBlockTransformed)
            {
                this.FlushFinalBlock();
            }
            this._stream.Close();
        }
    }
    finally
    {
        try
        {
            this._finalBlockTransformed = true;
            if (this._InputBuffer != null)
            {
                Array.Clear(this._InputBuffer, 0, this._InputBuffer.Length);
            }
            if (this._OutputBuffer != null)
            {
                Array.Clear(this._OutputBuffer, 0, this._OutputBuffer.Length);
            }
            this._InputBuffer = null;
            this._OutputBuffer = null;
            this._canRead = false;
            this._canWrite = false;
        }
        finally
        {
            base.Dispose(disposing);
        }
    }
}

注意:如您所见,有一条显式调用通过此行关闭流:

this._stream.Close();

答案 1 :(得分:0)

我认为你使用的所有对象都实现了IDisposable,所以如果我是你,我会将它们全部包含在使用语句中,这样它们就会自动为你清理,即

using(msencryptedcommand = new MemoryStream())
{
    ....
}