How do I read the public key from a signed C# exe

2019-02-13 17:59发布

I'm signing a dot net exe using

signcode.exe with an spc/pvk combo

The file needs to read its own Public Key at runtime in order to verify some data. I've gone down a number of different avenues.

I've tried

X509Certificate executingCert = X509Certificate.CreateFromSignedFile(exe);

executingCert is then null. I'm guessing signcode isn't creating an X509 signed file, though if there's a switch to change that I'm happy to go that way.

edited Turns out the above does work.... I had my null check backwards (!= != ==) :)

Assembly asm = Assembly.GetExecutingAssembly();
string exe = asm.Location;
X509Certificate executingCert = X509Certificate.CreateFromSignedFile(exe); 

if (executingCert != null)
{
    Console.WriteLine("Assembly is signed");
    byte[] assemblyKey = executingCert.GetPublicKey();
}

2条回答
Ridiculous、
2楼-- · 2019-02-13 18:38

Try something like that:

Assembly.GetEntryAssembly().GetName().GetPublicKey()

I used GetEntryAssembly in that case, but of course you can call the method on any loaded assembly.

查看更多
Juvenile、少年°
3楼-- · 2019-02-13 18:49

SignCode (for .Net 1.0 and 1.1) uses Authenticode signing, which as far as I'm aware, lacks a .Net Framework managed interface. You will likely need to use P/Invoke to call routines in Win32 API such as those found in this KB article: How To Get Information from Authenticode Signed Executables. Likely you'll need to use CryptQueryObject which will get you the certificate, which you will then likely have to find another routine to pull the public key from.

Check out this related StackOverflow question which has a lot of answers: WinVerifyTrust to check for a specific signature?

查看更多
登录 后发表回答