Hi @谭振华 , Welcome to Microsoft Q&A,
The canonicalization (C14N) process may differ depending on how you sign the document and how you certify it.
You are using xmlDoc.PreserveWhitespace = true;
, which preserves whitespace in the XML document. Make sure the inputs to the signing and verification processes are exactly the same, including any whitespace.
You set reference.Uri = "";
in the SignXmlDocumentWithCertificate
method. This indicates that the entire document is being signed, but it is critical that the structure of the document remains the same between signing and verification. Any changes, even minor ones, can render the signature invalid.
public static bool VerifyXmlDocumentSignature(XmlDocument xmlDoc, X509Certificate2 cert)
{
// Create a new SignedXml object and pass it the XmlDocument
SignedXml signedXml = new SignedXml(xmlDoc);
// Find the "Signature" node and load it
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");
if (nodeList.Count <= 0)
{
throw new CryptographicException("Signature not found.");
}
signedXml.LoadXml((XmlElement)nodeList[0]);
// Verify the signature
bool result = signedXml.CheckSignature(cert, true);
// Logging for debugging purposes
if (!result)
{
Console.WriteLine("Signature verification failed.");
}
return result;
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.