Verify XMLDSIG chain in .NET?

2020-03-30 02:26发布

问题:

I'm using XMLDSIG to sign a configuration file. I'd like my CA to be able to issue keys that can be used to sign XML. I'd then like to verify that the XML was signed with a key issued by my CA.

How do I get the signing certificate out of the SignedXml object? How do I follow the certificate chain back to a specific CA?

Note that the public key for my CA will be stored in my executable, rather than the certificate store.

回答1:

To attach arbitrary certificates to an XML-DSIG file, add an <X509Data> element. To do this in .NET, use:

signedXml.KeyInfo.AddClause(
    new KeyInfoX509Data(certificate, X509IncludeOption.WholeChain));

To extract the certificates from the XML file, use:

var certificates = signedXml.KeyInfo.OfType<KeyInfoX509Data>().Single();

You can then verify the chain by using the following:

var chain = new X509Chain();
chain.ChainPolicy.ExtraStore.AddRange(
    certificates.Cast<X509Certificate2>().ToArray());
var chainIsOk = chain.Build(signingCertificate);

To figure out which certificate was actually used for signing (and hence the value of signingCertificate), you need to find the included certificate that matches the key returned from CheckSignatureReturningKey.