簡體   English   中英

如何在C#中正確簽名XML文件?

[英]How to correctly sign an XML file in c#?

我有這樣的源文件:

<LicenseFile xmlns="">
<Object Id="Settings">
<ProductID xmlns="">P2</ProductID>
            <FirstName xmlns="">John</FirstName>
            <LastName xmlns="">Jackson</LastName>
</Object>
</LicenseFile>

我需要添加符號並接收這樣的文件:

    <LicenseFile xmlns="">
     <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
...
       <Object Id="Settings">
       <ProductID xmlns="">P2</ProductID>
                <FirstName xmlns="">John</FirstName>
                <LastName xmlns="">Jackson</LastName>
       </Object>
    </Signature>
    </LicenseFile>

但是我有這樣的結果文件:

    <LicenseFile xmlns="">
     <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
...
    </Signature>
    <Object Id="Settings">
       <ProductID xmlns="">P2</ProductID>
                <FirstName xmlns="">John</FirstName>
                <LastName xmlns="">Jackson</LastName>
    </Object>
    </LicenseFile>

我使用該代碼:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.Load(new XmlTextReader(FileName));
SignedXml signedXml = new SignedXml(doc);
signedXml.SigningKey = Key;
Signature XMLSignature = signedXml.Signature;
Reference reference = new Reference("#Settings");
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
XMLSignature.SignedInfo.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new RSAKeyValue((RSA)Key));
XMLSignature.KeyInfo = keyInfo;

// Compute the signature.
signedXml.ComputeSignature();

XmlElement xmlDigitalSignature = signedXml.GetXml();

// Append the element to the XML document.
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
if (doc.FirstChild is XmlDeclaration)
{
    doc.RemoveChild(doc.FirstChild);
}

// Save the signed XML document to a file specified
// using the passed string.
XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
doc.WriteTo(xmltw);
xmltw.Close();

什么不對? 日Thnx。

對象節點必須是簽名的子級,並且不能處於同一級別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM