473,783 Members | 2,577 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CryptographicEx ception 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 CryptographicEx ception. 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.xml e";

static void Main(string[] args)
{
EncryptFile(SOU RCE_XML_FILE_PA TH, ENCRYPTED_FILE_ PATH, MY_PASSWORD);
ReadEncryptedXm l(ENCRYPTED_FIL E_PATH, MY_PASSWORD); }

private static void ReadEncryptedXm l(string encryptedFilePa th, string
password) {
FileStream fileStreamSrc = null;
CryptoStream cstream = null;
StreamReader streamReader = null;
XmlTextReader xmlReader = null;

try {
fileStreamSrc = new FileStream(encr yptedFilePath, FileMode.Open,
FileAccess.Read );
cstream = CreateEncrypted Stream(fileStre amSrc, password,
CryptoStreamMod e.Read);

streamReader = new StreamReader(cs tream, Encoding.UTF8);
xmlReader = new XmlTextReader(s treamReader);

xmlReader.White spaceHandling = WhitespaceHandl ing.None;
xmlReader.MoveT oContent();

bool breakOut = false;
while (xmlReader.Node Type != XmlNodeType.End Element) {
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.Appen dChild(
retValue1.ReadN ode( xmlReader ));
breakOut = true;
break;
default:
xmlReader.Skip( );
break;
}

if (breakOut) {
break;
}
}

xmlReader.Close ();
streamReader.Cl ose();
cstream.Close() ;
fileStreamSrc.C lose();
}
catch (CryptographicE xception ex) {
Console.WriteLi ne(ex.ToString( ));
}
catch (Exception ex) {
Console.WriteLi ne(ex.ToString( ));
}
}

private static void EncryptFile(str ing sourceXmlFilePa th, string
destEncryptedFi lePath, string password) {
FileStream fileStreamSrc = null;
FileStream fileStreamDest = null;
CryptoStream cstream = null;

try {
fileStreamSrc = new FileStream(sour ceXmlFilePath, FileMode.Open,
FileAccess.Read );
fileStreamDest = new FileStream(dest EncryptedFilePa th, FileMode.Create ,
FileAccess.Writ e);

long rdlen = 0;
long totlen = fileStreamSrc.L ength;
int len;

cstream = CreateEncrypted Stream(fileStre amDest, password,
CryptoStreamMod e.Write);

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

cstream.Close() ;
fileStreamDest. Close();
fileStreamSrc.C lose();
}
catch (Exception ex) {
Console.WriteLi ne(ex.ToString( ));
}
}

private static CryptoStream CreateEncrypted Stream( Stream baseStream, string
password, CryptoStreamMod e streamMode ) {
CryptoStream retValue = null;
SymmetricAlgori thm cryptoAlgorithm = Rijndael.Create ();
PasswordDeriveB ytes pdb = new PasswordDeriveB ytes( 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 == CryptoStreamMod e.Read ) {
retValue = new CryptoStream( baseStream,
cryptoAlgorithm .CreateDecrypto r(), streamMode );
}
else {
retValue = new CryptoStream( baseStream,
cryptoAlgorithm .CreateEncrypto r(), streamMode );
}

return retValue;
}

private static void DecryptFile(str ing encryptedFilePa th, string
destinationFile Path, string password) {
FileStream fileStreamSrc = null;
CryptoStream cstream = null;

try {
fileStreamSrc = new FileStream(encr yptedFilePath, FileMode.Open,
FileAccess.Read );
cstream = CreateEncrypted Stream(fileStre amSrc, password,
CryptoStreamMod e.Read);

StreamWriter fsDecrypted = new
StreamWriter(de stinationFilePa th);
fsDecrypted.Wri te(new StreamReader(cs tream).ReadToEn d());
fsDecrypted.Flu sh();
fsDecrypted.Clo se();

cstream.Close() ;
fileStreamSrc.C lose();
}
catch (Exception ex) {
Console.WriteLi ne(ex.ToString( ));
}
}

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

<States>
<State>
<Name>Illinoi s</Name>
<Population>Unk nown</Population>
<Data>
<Item type="MyType" number="1">
<SubItem utcTime="2004-09-12 17:00:00Z" timeTicks="6323 06052000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 17:00:00Z" timeTicks="6323 06052000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 20:15:00Z" timeTicks="6323 06169000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 20:15:00Z" timeTicks="6323 06169000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-12 20:15:00Z" timeTicks="6323 06169000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-13 00:30:00Z" timeTicks="6323 06322000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-14 01:00:00Z" timeTicks="6323 07204000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:05:00Z" timeTicks="6323 12211000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-20 00:30:00Z" timeTicks="6323 12370000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-21 01:00:00Z" timeTicks="6323 13252000000000"
attr1="False" attr2="False" />
</Item>
<Item type="MyType" number="2">
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 17:00:00Z" timeTicks="6323 12100000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:05:00Z" timeTicks="6323 12211000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-19 20:15:00Z" timeTicks="6323 12217000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-20 00:30:00Z" timeTicks="6323 12370000000000"
attr1="False" attr2="False" />
<SubItem utcTime="2004-09-21 01:00:00Z" timeTicks="6323 13252000000000"
attr1="False" attr2="False" />
</Item>
</Data>
</State>
</States>

Nov 17 '05 #1
6 1924
Tim Barg <Ti*****@discus sions.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 CryptographicEx ception. 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.co m>
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*****@discus sions.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 CryptographicEx ception. 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.co m>
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**@discussio ns.microsoft.co m> 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.xml e";

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.xml e";

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.co m>
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.xml e";

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.xml e";

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**@discussio ns.microsoft.co m> 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.co m>
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
2424
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 Transformation stop working at all for the whole AppDomain until I restart it. Am I using "this.GetType().Assembly.Evidence" incorrectly? And another question is what if I pass Evidence that I've created using CreateEvidenceForUrl(@"my working...
1
3110
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 receive an exception System.Security.Cryptography.CryptographicException (incorrect parameter)
4
1907
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 document validates ok in xmlSpy but it fails in VS2003. Is there any article or fix for this? Thnaks in advance. Error: ======
2
5593
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 XmlNodeType.Element: Console.WriteLine("<{0}>", reader.Name); break;
1
2769
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 error. (System.Security.Cryptography.CryptographicException: Bad Data. at System.Security.Cryptography.CryptoAPITransform._DecryptData(IntPtr hKey, Byte rgb, Int32 ib, Int32 cb, Boolean fDone) at...
1
1605
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 times it is a client browser such as IE). I'm curious if anyone has some insight as to why this would be happening, if there is a way to resolve this. If it was just a web crawler I'd ask if we should even care. The error is - ...
7
1191
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 XmlTextReader(Me.Server.MapPath("staff.xml")) Try Do While xmlrdr.Read() Loop xmlrdr.Close() lblWellFormed.Text = "Well-Formed"
6
6308
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 CryptographicException "the parameter is incorrect" Here's the stack trace: System.Security.Cryptography.CryptographicException: The parameter is
4
2635
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 who originally did this work for her). I know some programming languages, but this is not one of them and I am hoping someone can help me. My client has a real estate website and I get the following error (per her complaint) when I try and sign up...
0
10315
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10083
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9946
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6737
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5379
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.