问题
I'm trying to sign a XML document with a reference to the KeyInfo node but I'm getting "malformed reference element" exception after calling the method "ComputeSignature".
This is my code:
signedXml.SigningKey = certificate.PrivateKey;
if (!signParameters.IncludeCertificateInSignature) return;
var certificateKeyInfo = new KeyInfo();
certificateKeyInfo.AddClause(new KeyInfoX509Data(certificate));
signedXml.KeyInfo = certificateKeyInfo;
signedXml.KeyInfo.Id = "xmldsig-keyinfo";
signedXml.AddReference(new Reference("#xmldsig-keyinfo"));
If I remove the "#xmldsig-keyinfo", it works, but I get the reference with the entire document, I need the reference with the KeyInfo tag.
回答1:
I finally found the answer, I can't add the KeyInfoId reference because the xmlElement is not created yet in the XMLDoc; so I implemented the SigneXML class and return the XML directly from the keyInfo.
public override XmlElement GetIdElement(XmlDocument doc, string id)
{
if (String.Compare(id, this.KeyInfo.Id, StringComparison.OrdinalIgnoreCase) == 0)
return this.KeyInfo.GetXml();
else
return base.GetIdElement(doc, id);
}
I hope it helps!!
回答2:
In my case, after days trapped. It was the Reference.uri. I was saving it as "# 1". The XML was.
<getTest>
<item ID="1">
<Seed>123</Seed>
</item>
</getTest>
that worked ok on Windows Server 2003 but failed on developer machine on Windows 10 and Windows Server 2012 R2 server. It was falling into ComputeSignature method.
Finally I read that the ID cannot be a number, if it must start with a letter. https://www.w3.org/TR/html401/types.html#type-name I changed it to test reference.uri = "#test" and the base XML I changed how show below.
<getTest>
<item ID="test">
<Seed>123</Seed>
</item>
</getTest>
and voila, it works in all environments.
There are some patches in the S.O. new ones that cause it to fail and not work in the old ones that did not have these patches and that are the ones that place that restriction.
KB3140745
KB3140768
KB3140743
KB3073930
来源:https://stackoverflow.com/questions/37594051/malformed-reference-element-exception-signing-a-xml-file