473,387 Members | 1,691 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

CryptographicException when closing XmlTextReader

I am using a CryptoStream to encrypt and then save an xml file. However,
when reading it back in, I am getting a CryptographicException. I am hitting
this because I have some large xml files ( > 10MB) and I only need a certain
node...I use an XmlTextReader to find the node I need, and then attempt to
abort reading in the rest of the xml, but when I close the XmlTextReader I
get the exception. I've included some sample code and xml that should
exhibit the behavior.

Note: If I use Skip() to get to the end of the xml, then I don't get
exceptions, but as I mentioned, the files I'm dealing with can be large and
Skip() takes quite a while to skip over nodes that I don't care about which
really hurts performance. Any ideas?

--------- SAMPLE SOURCE CODE ---------

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Xml;

private const string MY_PASSWORD = "test"; private const string
SOURCE_XML_FILE_PATH = @"C:\Sample.xml"; private const string
ENCRYPTED_FILE_PATH = @"C:\Sample.xmle";

static void Main(string[] args)
{
EncryptFile(SOURCE_XML_FILE_PATH, ENCRYPTED_FILE_PATH, MY_PASSWORD);
ReadEncryptedXml(ENCRYPTED_FILE_PATH, MY_PASSWORD); }

private static void ReadEncryptedXml(string encryptedFilePath, string
password) {
FileStream fileStreamSrc = null;
CryptoStream cstream = null;
StreamReader streamReader = null;
XmlTextReader xmlReader = null;

try {
fileStreamSrc = new FileStream(encryptedFilePath, FileMode.Open,
FileAccess.Read);
cstream = CreateEncryptedStream(fileStreamSrc, password,
CryptoStreamMode.Read);

streamReader = new StreamReader(cstream, Encoding.UTF8);
xmlReader = new XmlTextReader(streamReader);

xmlReader.WhitespaceHandling = WhitespaceHandling.None;
xmlReader.MoveToContent();

bool breakOut = false;
while (xmlReader.NodeType != XmlNodeType.EndElement) {
switch (xmlReader.Name) {
case "States":
xmlReader.Read();
break;
case "State":
xmlReader.Read();
break;
case "Name":
xmlReader.Skip();
break;
case "Population":
XmlDocument retValue1 = new
XmlDocument();
retValue1.AppendChild(
retValue1.ReadNode( xmlReader ));
breakOut = true;
break;
default:
xmlReader.Skip();
break;
}

if (breakOut) {
break;
}
}

xmlReader.Close();
streamReader.Close();
cstream.Close();
fileStreamSrc.Close();
}
catch (CryptographicException ex) {
Console.WriteLine(ex.ToString());
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}

private static void EncryptFile(string sourceXmlFilePath, string
destEncryptedFilePath, string password) {
FileStream fileStreamSrc = null;
FileStream fileStreamDest = null;
CryptoStream cstream = null;

try {
fileStreamSrc = new FileStream(sourceXmlFilePath, FileMode.Open,
FileAccess.Read);
fileStreamDest = new FileStream(destEncryptedFilePath, FileMode.Create,
FileAccess.Write);

long rdlen = 0;
long totlen = fileStreamSrc.Length;
int len;

cstream = CreateEncryptedStream(fileStreamDest, password,
CryptoStreamMode.Write);

// Read from input file, encrypt and write to output file
byte[] b = new byte[1024];
while(rdlen < totlen) {
len = fileStreamSrc.Read(b, 0, b.Length);
cstream.Write(b, 0, len);
rdlen = rdlen + len;
}

cstream.Close();
fileStreamDest.Close();
fileStreamSrc.Close();
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}

private static CryptoStream CreateEncryptedStream( Stream baseStream, string
password, CryptoStreamMode streamMode ) {
CryptoStream retValue = null;
SymmetricAlgorithm cryptoAlgorithm = Rijndael.Create();
PasswordDeriveBytes pdb = new PasswordDeriveBytes( password,
new byte[]{
0x12, 0x34, 0x56,
0x78, 0x90,
0xAB,
0xCD, 0xEF,
0x10,
0x11, 0x22,
0x33,
0x44 });
cryptoAlgorithm.Key = pdb.GetBytes( 32 );
cryptoAlgorithm.IV = pdb.GetBytes( 16 );

if( streamMode == CryptoStreamMode.Read ) {
retValue = new CryptoStream( baseStream,
cryptoAlgorithm.CreateDecryptor(), streamMode );
}
else {
retValue = new CryptoStream( baseStream,
cryptoAlgorithm.CreateEncryptor(), streamMode );
}

return retValue;
}

private static void DecryptFile(string encryptedFilePath, string
destinationFilePath, string password) {
FileStream fileStreamSrc = null;
CryptoStream cstream = null;

try {
fileStreamSrc = new FileStream(encryptedFilePath, FileMode.Open,
FileAccess.Read);
cstream = CreateEncryptedStream(fileStreamSrc, password,
CryptoStreamMode.Read);

StreamWriter fsDecrypted = new
StreamWriter(destinationFilePath);
fsDecrypted.Write(new StreamReader(cstream).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();

cstream.Close();
fileStreamSrc.Close();
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}

--------- SAMPLE XML ---------

<States>
<State>
<Name>Illinois</Name>
<Population>Unknown</Population>
<Data>
<Item type="MyType" number="1">
<SubItem utcTime="2004-09-12 17:00:00Z" timeTicks="632306052000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 17:00:00Z" timeTicks="632306052000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 20:15:00Z" timeTicks="632306169000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 20:15:00Z" timeTicks="632306169000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 20:15:00Z" timeTicks="632306169000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-13 00:30:00Z" timeTicks="632306322000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-14 01:00:00Z" timeTicks="632307204000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:05:00Z" timeTicks="632312211000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-20 00:30:00Z" timeTicks="632312370000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-21 01:00:00Z" timeTicks="632313252000000000"
attr1="False" attr2="False" />
</Item>
<Item type="MyType" number="2">
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="632312100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:05:00Z" timeTicks="632312211000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="632312217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-20 00:30:00Z" timeTicks="632312370000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-21 01:00:00Z" timeTicks="632313252000000000"
attr1="False" attr2="False" />
</Item>
</Data>
</State>
</States>

Nov 17 '05 #1
6 1898
Tim Barg <Ti*****@discussions.microsoft.com> wrote:
I am using a CryptoStream to encrypt and then save an xml file. However,
when reading it back in, I am getting a CryptographicException. I am hitting
this because I have some large xml files ( > 10MB) and I only need a certain
node...I use an XmlTextReader to find the node I need, and then attempt to
abort reading in the rest of the xml, but when I close the XmlTextReader I
get the exception. I've included some sample code and xml that should
exhibit the behavior.

Note: If I use Skip() to get to the end of the xml, then I don't get
exceptions, but as I mentioned, the files I'm dealing with can be large and
Skip() takes quite a while to skip over nodes that I don't care about which
really hurts performance. Any ideas?


It would really help if:

a) you could post a short but *complete* program - one we can actually
compile and run, without having to fix up a load of the code

b) you could tell us what the exception message is

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Tim Barg <Ti*****@discussions.microsoft.com> wrote:
I am using a CryptoStream to encrypt and then save an xml file. However,
when reading it back in, I am getting a CryptographicException. I am hitting
this because I have some large xml files ( > 10MB) and I only need a certain
node...I use an XmlTextReader to find the node I need, and then attempt to
abort reading in the rest of the xml, but when I close the XmlTextReader I
get the exception. I've included some sample code and xml that should
exhibit the behavior.

Note: If I use Skip() to get to the end of the xml, then I don't get
exceptions, but as I mentioned, the files I'm dealing with can be large and
Skip() takes quite a while to skip over nodes that I don't care about which
really hurts performance. Any ideas?


<snip>

Having looked at this for a few minutes (after fixing up the code you
posted) you can reproduce this without any XML, or even any files. The
problem is that closing a CryptoStream half way through tries to flush
the final buffer, which causes the exception.

It looks like a bug in the framework to me - I suggest you report it to
Microsoft at
http://lab.msdn.microsoft.com/productfeedback/

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
> It would really help if:

a) you could post a short but *complete* program - one we can actually
compile and run, without having to fix up a load of the code


What exactly did you have to "fix up"? I copied the code into a new console
project and it ran fine without any modification.
Nov 17 '05 #4
Matt <Ma**@discussions.microsoft.com> wrote:
It would really help if:

a) you could post a short but *complete* program - one we can actually
compile and run, without having to fix up a load of the code


What exactly did you have to "fix up"? I copied the code into a new console
project and it ran fine without any modification.


Sorry, but you really didn't. Your code doesn't declare a class, to
start with...

In fact, putting the code in a class was all that needed doing - but
that was made fairly unclear due to the formatting of the code. For
instance, the first code block:

private const string MY_PASSWORD = "test"; private const string
SOURCE_XML_FILE_PATH = @"C:\Sample.xml"; private const string
ENCRYPTED_FILE_PATH = @"C:\Sample.xmle";

would have been rather clearer as:

private const string MY_PASSWORD = "test";
private const string SOURCE_XML_FILE_PATH = @"C:\Sample.xml";
private const string ENCRYPTED_FILE_PATH = @"C:\Sample.xmle";

Similarly, at first sight Main (as posted) doesn't appear to have any
closing brace - it's "hidden" at the end of the line.

It's worth considering how the code will appear to someone else when
posted, bearing in mind that that person will never have seen the code
before.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
> Sorry, but you really didn't. Your code doesn't declare a class, to
start with...

In fact, putting the code in a class was all that needed doing - but
that was made fairly unclear due to the formatting of the code. For
instance, the first code block:

private const string MY_PASSWORD = "test"; private const string
SOURCE_XML_FILE_PATH = @"C:\Sample.xml"; private const string
ENCRYPTED_FILE_PATH = @"C:\Sample.xmle";

would have been rather clearer as:

private const string MY_PASSWORD = "test";
private const string SOURCE_XML_FILE_PATH = @"C:\Sample.xml";
private const string ENCRYPTED_FILE_PATH = @"C:\Sample.xmle";

Similarly, at first sight Main (as posted) doesn't appear to have any
closing brace - it's "hidden" at the end of the line.

It's worth considering how the code will appear to someone else when
posted, bearing in mind that that person will never have seen the code
before.


Ah, you're talking formatting issues. Yes, I agree. We posted the message
through the msdn newsgroup site (http://msdn.microsoft.com/newsgroups) which
appears to have thrown off the line breaks in some weird way.

Also, for reference, we would have preferred to attach a complete program,
but did not see any obvious way to attach files to a post using the msdn site.

Anyway, we suspected it was a bug in the framework (we're using .NET 1.1
Framework). Thanks for taking a look.

Matt

Nov 17 '05 #6
Matt <Ma**@discussions.microsoft.com> wrote:
It's worth considering how the code will appear to someone else when
posted, bearing in mind that that person will never have seen the code
before.
Ah, you're talking formatting issues.


Only partly - even without the formatting issues, your code still
didn't declare any classes, going straight from the using directives to
a member declaration.
Yes, I agree. We posted the message
through the msdn newsgroup site (http://msdn.microsoft.com/newsgroups) which
appears to have thrown off the line breaks in some weird way.
It's generally a better idea to use a "real" newsreader IMO, pointing
at news.microsoft.com.
Also, for reference, we would have preferred to attach a complete program,
but did not see any obvious way to attach files to a post using the msdn site.

Anyway, we suspected it was a bug in the framework (we're using .NET 1.1
Framework). Thanks for taking a look.


Yup, it does look like it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Tod Johnson | last post by:
Not so long I've found really strange bug in the .NET. It seems that Evidence that I've got from the current executing Assembly is somehow expired (it happens suddenly after about month) and Xslt...
1
by: jasonjbwalton | last post by:
Hi I am implementing a solution based upon Sitecore CMS version 4.3.2.6 ..Net 1.1 on a Windows 2003 server We are experiencing an error once in a while when transforming XML with XSLT. We...
4
by: Tomas Rivas | last post by:
I am trying to validate an xml file and schema and when I am trying to validate I am getting the following error. I have been trying to come out with a solution but I have failed so far. The...
2
by: Mitch | last post by:
I have some simple HTML I'm trying to read with the XMLTextReader. As in the MSDS examples, I set up a loop to read each XML node: while (reader.Read()) { switch (reader.NodeType) { case...
1
by: muthu | last post by:
Hi, I have two web applications running on my machine.The application is developed using asp.net 1.1 and vb.net.When i try to run both the applications in the same browsers, i get the following...
1
by: Brad | last post by:
Our .Net 2 web apps recently started getting CryptographicExceptions from WebResource.axd, and these almost always seem to be when the client is a web crawler...most notably googlebot (but a few...
7
by: puginews | last post by:
I was wondering when you create a new xmltextreader (or any other object for that matter), is it destroyed/closed (memory/resources freed) when an exception occurs ? Dim xmlrdr As New...
6
by: andrew | last post by:
Hi, I have a web service application written in C# .NET 1.1 using MD5CryptoServiceProvider.ComputeHash(Byte) The problem is that after a while(web service processes requests) the call throws...
4
by: Porty | last post by:
Hi all, I admittedly don't know the first thing about .NET. I have a new client who has been having problems on her website and asked me to look into it (she has lost contact with the programmer...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.