/// <summary> /// Verifies the specified XML text signature. /// </summary> /// <param name="xmlText">The XML text.</param> /// <param name="certificate">The certificate.</param> ///<returns>True if the signature is valid, false otherwise</returns> public static bool VerifyDocument(string xmlText, X509Certificate2 certificate) { var xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.LoadXml(xmlText); XmlElement signatureElement = XmlSignature.GetElementUnderRoot(xmlDoc.DocumentElement, "Signature", "http://www.w3.org/2000/09/xmldsig#") as XmlElement; var result = XmlSignature.CheckSignature(xmlDoc, certificate, signatureElement); return(result); }
/// <summary> /// Tries to verify the specified XML text signature. /// </summary> /// <param name="xmlText">The XML text.</param> /// <param name="elementName">The name of the element signature to be verified.</param> /// <param name="elementNamespace">The namespace of the element signature to be verified.</param> /// <param name="isValidSignature">True if the signature is valid and placed properly, false otherwise.</param> /// <returns>True if the verifying was possible, false otherwise.</returns> public static bool TryVerifyElement(string xmlText, string elementName, string elementNamespace, out bool isValidSignature) { isValidSignature = false; if (String.IsNullOrEmpty(elementName)) { return(false); } var xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.LoadXml(xmlText); var elements = xmlDoc.GetElementsByTagName(elementName, elementNamespace); if (elements.Count == 0) { return(false); } XmlElement elementToSign = elements[0] as XmlElement; var xmlElementDoc = new XmlDocument(); xmlElementDoc.PreserveWhitespace = true; xmlElementDoc.LoadXml(elementToSign.OuterXml); //XmlElement element = elementToSign; //var keyInfo = XmlSignature.GetElementUnderRoot(element as XmlElement, "KeyInfo"); //var x509Data = XmlSignature.GetElementUnderRoot(keyInfo as XmlElement, "X509Data"); //var x509Certificate = XmlSignature.GetElementUnderRoot(x509Data as XmlElement, "X509Certificate"); //byte[] certificate = Encoding.Unicode.GetBytes(x509Certificate.InnerText); X509Certificate2 cert = ExtractCertificate(xmlElementDoc); // the signature should have been placed inside its 'MndtAccptncRpt' element (more specific, inside a <SplmtryData><Envlp>....</Envlp></SplmtryData> container) isValidSignature = XmlSignature.CheckSignature(xmlElementDoc, cert, GetEmandatesSignatureElement(xmlElementDoc.DocumentElement)); return(true); }