bbs*_*had 2 .net c# asp.net encryption try-catch
我的网站上有以下代码.它将URL查询作为名为commandencrypted的字符串.我有一个try/catch/finally块,将加密的命令复制到一个MemoryStream,然后解密回一个字符串.如果发生在try块中的任何错误,他们在catch块处理.不过,我要确保所使用的任何资源finally块中被关闭.当提供无效的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();
}
}
Run Code Online (Sandbox Code Playgroud)
以下未处理的异常:System.Security.Cryptography.CryptographicException:数据的长度来解密是无效的.在System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(字节[] INPUTBUFFER,的Int32 inputOffset,的Int32 inputCount)在System.Security.Cryptography.CryptoStream.FlushFinalBlock()在System.Security.Cryptography.CryptoStream.Dispose(布尔处置)在系统update.ashx中的dongleupdate.ProcessRequest(HttpContext context)中的.IO.Stream.Close():位于System.Web.HttpApplication的System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()的第92行. ExecuteStep(IExecutionStep step,Boolean&completedSynchronously)URL Referrer:用户代理:Mozilla/5.0(Windows NT 6.1; WOW64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/30.0.1599.69 Safari/537.
编辑:
我将代码更改为使用语句.这也是确保所有资源都关闭的有效方法吗?
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;
}
Run Code Online (Sandbox Code Playgroud)
包装你CryptoStream的using块,然后它会通过自动关闭和处置你Dispose Pattern,就像这样:
using(csencryptedcommand = new CryptoStream(msencryptedcommand,
rmencryptedcommand.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
// Do things with crypto stream here
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请阅读Statement(C#参考)文档.
更新:
使用反射器,这里是代码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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如您所见,有一条显式调用通过此行关闭流:
this._stream.Close();
Run Code Online (Sandbox Code Playgroud)