Signing an XML document with a code-signing certificate in .Net

Hi!

Microsoft have a good example of how to sign an XML document in their SDK documentation at How to: Sign XML Documents with Digital Signatures | Microsoft Learn.

The trouble with this example is that it generates the code-signing key. There are other examples of how to put the generated key in a “key container” and to retrieve or remove it from there, but there are no examples of how to use an existing certificate as, for example, obtained from Comodo. This post shows how to modify the above-mentioned example to use a Comodo code-signing certificate.

  1. If the certificate is already in a file with a .pfx extension, skip this step. If the certificate is in the form of MyCert.pvk and MyCert.spc files, then run the pvk2pfx program that is supplied with the Microsoft Windows SDK to create a certificate, with private key, in pfx format:

    pvk2pfx -pvk MyCert.pvk -pi pvkpassword -spc MyCert.spc

This creates MyCert.pfx with the same password as the .pvk file.

  1. Replace the following lines in Microsoft’s example:

            // Create a new CspParameters object to specify
            // a key container.
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

            // Create a new RSA signing key and save it in the container. 
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

with:


            // Load the certificate from the pfx file.
            X509Certificate2 certificate = new X509Certificate2 ("MyCert.pfx", "pvkpassword");

            // Set the rsaKey to the certificate's private key
            RSACryptoServiceProvider rsaKey = certificate.PrivateKey;   


It is also necessary to add a: “using System.Security.Cryptography.X509Certificates;” name space near the beginning of the example.

The mysterious RSACryptoServiceProvider class is actually the certificate’s private key.

The modified example loads the certificate directly from its file, but if you hunt through Microsoft’s SDK examples relating to X509Certificates, you will also find examples of how to retrieve a certificate from the certificate store.

regards,
Alan.