The Windows SDK ships with a tool called signtool.exe that lets you sign a file with a certificate. I need to do the same thing but in a background service so I'm on the lookout for a library (preferably managed code, but COM will do) to do the same thing. Any ideas?
Found the answer. Here's how to use an X.509 certificate to sign a file in .NET:
CmsSigner signer = new CmsSigner();
signer.Certificate = new X509Certificate2(certificate);
SignedCms content = new SignedCms(new ContentInfo(File.ReadAllBytes(fileToSign)));
content.ComputeSignature(signer, true);
byte[] signedFile = content.Encode();
string signedFileName = fileToSign + ".signed";
File.WriteAllBytes(signedFileName, signedFile);
Console.WriteLine("Signed file: " + signedFileName);
Here, certificate is the path to the .pfx file containing the certificate and fileToSign is the file to sign.
SignTool is using CAPICOM which is the COM wrapper for the Crypto API. You can use either one. If you're going with CAPICOM, you can check the information here.