gpt4 book ai didi

c# - Try/Catch/Finally 加密资源

转载 作者:行者123 更新时间:2023-12-02 04:48:05 26 4
gpt4 key购买 nike

我的网站上有以下代码。它将 URL 查询作为名为 commandencrypted 的字符串。我有一个 try/catch/finally block ,它将加密命令复制到内存流,然后将其解密回字符串。如果 try block 中发生任何错误,它们将在 catch block 中处理。但是,我想确保在 finally block 中关闭所有使用的资源。当提供无效的 URL 查询命令时,我在尝试关闭 csencryptedcommand 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();
}
}

The following unhandled exception occurred: System.Security.Cryptography.CryptographicException: Length of the data to decrypt is invalid. at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at dongleupdate.ProcessRequest(HttpContext context) in update.ashx:line 92 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) URL Referrer: User Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36 Request URL: update.ashx?aa

编辑:

我更改了代码以使用 using 语句。这是否也是确保所有资源关闭的有效方法?

    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;
}

最佳答案

将你的 CryptoStream 包裹在 using block 中,然后它将自动关闭并通过 Dispose Pattern 为你处理,就像这样:

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

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

更新:

使用 Reflector ,这里是 CryptoStreamDispose 方法的代码:

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();

关于c# - Try/Catch/Finally 加密资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19408478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com