How to canonicalize an XML Document

  • Thread starter Thread starter Pollux
  • Start date Start date
P

Pollux

Hi

I previously posted a question which hasn't been answered, so I figured
it must have been too complicated. I must admit that I didn't make it
very easy to follow. In fact, the information I need is quite simple.
How to canonicalize an XML Document in C#? Consider the following code:

XmlDocument myDoc = new XmlDocument();
myDoc.Load("somefile.xml");
XmlDsigC14NTransform t = new XmlDsigC14NTransform();
t.LoadInput (myDoc);
Stream s = (Stream) t.GetOutput(typeof(Stream));
SHA1 sha1 = SHA1.Create();

byte[] hash = sha1.ComputeHash(s);


Does s represent a stream of a canonicalized document?
 
Pollux said:
XmlDocument myDoc = new XmlDocument();
myDoc.Load("somefile.xml");
XmlDsigC14NTransform t = new XmlDsigC14NTransform();
t.LoadInput (myDoc);
Stream s = (Stream) t.GetOutput(typeof(Stream)); : :
Does s represent a stream of a canonicalized document?

Yes.

You can examine the document in s with,

Console.WriteLine( new StreamReader( s).ReadToEnd( ));

Note the Java code posed in your original post used the following
canonicalization method,

http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments

which corresponds to the XmlDsigC14NWithCommentsTransform
class. This only impacts you if "something.xml" contains comments,
otherwise the two canonicalizations are the same. In your particular
case this difference doesn't apply to this document (because you're
selecting the Body to sign and your sample document had no
comments within the Body), but you should use the right Transform
so that you can successfully verify the signatures on instance docs
that do have comments.


Derek Harmon
 
Back
Top