C#为什么XmlDsigC14NTransform从xml中删除所有空格

时间:2013-07-22 06:45:20

标签: c# xml canonicalization xml-dsig

我有XmlDsigC14NTransform的问题。我试图重复一些例子 http://www.di-mgt.com.au/xmldsig2.html(部分编写规范化的SignedInfo元素并计算其SignatureValue) 但是我的代码从xml中丢失了空格,我无法获得正确的hexdump。

我的C#代码:

 XmlDocument signedInfoXml = new XmlDocument();
 signedInfoXml.Load(@"C:\temp\new_sign.txt");

 XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform();
 xmlTransform.LoadInput(signedInfoXml);
 MemoryStream memoryStream = (MemoryStream)xmlTransform.GetOutput();
 return  BitConverter.ToString(memoryStream.ToArray()).Replace("-"," ");

源Xml(来自文件C:\ temp \ new_sign.txt):

<SignedInfo  xmlns="http://www.w3.org/2000/09/xmldsig#">
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      <Reference URI="">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <DigestValue>UWuYTYug10J1k5hKfonxthgrAR8=</DigestValue>
      </Reference>
    </SignedInfo>

如何将空格保存到我的xml中并获得规范化的xml,如样本(http://www.di-mgt.com.au/xmldsig2.html)?

1 个答案:

答案 0 :(得分:1)

您可以在XMLDocument上设置一个标志:

    // Create a new XML document.
    XmlDocument xmlDocument = new XmlDocument();

    // Format using white spaces.
    xmlDocument.PreserveWhitespace = true;

    // Load the XML file into the document. 
    xmlDocument.Load("file.xml");