.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

CA2202 using CryptoStream

Posted By:      Posted Date: September 27, 2010    Points: 0   Category :ASP.Net

Hi all,

the code below generates a CA2202 in code analysis - do not dispose of objects more than once. Given that I need access to the memory stream after I have called the CryptoStream write method I can't set the ms variable to null until the end of the try block and this causes the CA2202.

Has anyone got any thoughts on how to improve this code to eleminate the error.




public static byte[] Encrypt(byte[] clearData, byte[] key, byte[] initializationVector)
	byte[] encryptedData = null;

	MemoryStream ms = null;
		ms = new MemoryStream();
		using (Rijndael alg = Rijndael.Create())
			alg.Key = key;
			alg.IV = initializationVector;
			using (CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
				cs.Write(clearData, 0, clearData.Length);
				encryptedData = ms.ToArray();
				ms = null;
		if (ms != null)
	return encryptedData;


View Complete Post

More Related Resource Links

Problems Getting CryptoStream, NetworkStream, and Rijndael To Work Together

I created a simple example to test out using CryptoStreams with Networkstreams for transferring Rijndael encrypted data, but can't get it to work properly. The problem seems to be (this is my understanding of it) that it will only send data in block sizes, which would be fine, but it seems like you need to fill up a another full block size before it will actually send the data you initially wanted to send(and then you have written stuff to the stream that hasn't been sent yet but was added just to get the previous data to send). I cannot use flushfinalblock, as I'm keeping the stream open. If you close the stream, it works properly(I assume it's forcing the flush), which is why the same code works perfectly fine with a FileStream. 

Anyway, I've read a few things on the web where people have run into the same problems, I've just haven't found any solutions. People are calling flushfinalblock or writing to the stream twice to get it to send something, which are poor workarounds for the actual problem. And then others just say don't use Cryptostreams and networkstreams together. Does this really not work? MSDN has a small cryptostream/networkstream example, and my guess is it only works because they close the connection. 

Below is the code I used client side for the most part. Not doing anything crazy - I feel lik
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend