Validate multiple URI-specific signatures in XML

So I’m trying to write an XML document to send to a web service, but the specification forces me to sign each part of the document separately, referencing it through an URI via id. So I did. But when I send it, their response is just “invalid signature”.

The problem is, the validator I pass the document through before sending to them says the document is correctly signed. So probably my validator is wrong. But there seems to be very few question addressing this problem exactly: found some people asking about multiple root level signatures, but just one with multiple elements signatures. I tried adapting the code from the answer but it stills says the xml is fine. Can someone lend me a help with this?

The code (if someone needs the previous version I could edit it in too):

public static bool Validate(Stream signedXmlDocumentStream) { XmlNodeList documentSignatures = GetSignatures(signedXmlDocumentStream); foreach (XmlElement documentSignature in documentSignatures) { XmlDocument doc = new XmlDocument(); doc.LoadXml(documentSignature.ParentNode.OuterXml); XmlElement nodeSignature = doc.SelectSingleNode("//*[local-name()='Signature']") as XmlElement; //Left this comment from the original code: This variable is the same as node, just in doc instead of xml (important distinction) SignedXml signedXml = new SignedXml(nodeSignature.ParentNode as XmlElement); signedXml.LoadXml(documentSignature); X509Certificate2 certificate = null; foreach (KeyInfoClause clause in signedXml.KeyInfo) { KeyInfoX509Data data = clause as KeyInfoX509Data; if (data?.Certificates.Count > 0) certificate = (X509Certificate2)data.Certificates[0]; } if (certificate == null || !signedXml.CheckSignature(certificate, verifySignatureOnly: true)) return false; } return true; } 

submitted by /u/cocainecringefest
[link] [comments]

Leave a Reply