Search code examples
c#.netcertificatesignedxml

How to verify certificate in SignedXml against machine store


I would like to verify the signature in a SignedXml against the certificates in the machine store. This code is used to verify the signature:

internal bool VerifySignature(XmlDocument xml)
{
    var signedXml = new SignedXml(xml);
    var nsMgr = new XmlNamespaceManager(xml.NameTable);
    nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
    signedXml.LoadXml((XmlElement)xml.SelectSingleNode("//ds:Signature", nsMgr));
    return signedXml.CheckSignature();
}

The signature verifies fine, but only against itself and not against the certificates installed on the machine. Is there a way to check it against the root certificates in the local certificate store as well?


Solution

  • If anyone is interested, I used the CheckSignature(X509Certificate2, Boolean) method. I got the certificate from the Signature object and checked it like this:

    var x509data = signedXml.Signature.KeyInfo.OfType<KeyInfoX509Data>().First();
    var verified = false;
    if(x509data != null)
    {
        var cert = x509data.Certificates[0] as X509Certificate2;
        verified = cert != null && signedXml.CheckSignature(cert, false);
    }
    return verified;