views:

644

answers:

4

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.

+2  A: 

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.

On Freund
Found my answer. Documentation on using the CAPICOM library to do the signing here:http://msdn.microsoft.com/en-us/library/aa387760(VS.85).aspxSince the CAPICOM API is deprecated, this page shows what the .NET replacements are: http://msdn.microsoft.com/en-us/library/cc778518(VS.85).aspx
Arun
A: 

You can't just script your way around it? Write a simple batch file that gives it the correct arguments and input? That is atleast what we do when we see this problem on a UNIX server.

tomjen
Probably because he can't assume that it's deployed on the target computer and the license probably prohibits redistribution.
On Freund
A: 

Hi,

I used this sample code to sign an executable file. After signing the file, the generated executable is not a valid application. And the file properties don't show the signature.

I receive this error when I double click on the signed file renamed as .exe (removing the .signed) :

The version of this file is not compatible with the version of Windows you're running. Check your computer's system information to see whether you need an x86 (32-bit) or x64 (64-bit) version of the program, and then contact the software publisher.

I'm running Windows Vista 64 bits.

Any ideas ?

Sebastien
A: 

I'm getting the same problem as Sebastien. Looking into the API's, it appears that this is for signing enveloped messages. Authenticode -- the code-signing that signtool does -- is different, which is why the EXE doesn't run after the signing.

I'm still looking for alternatives.

Tom Canham