Search code examples
c#.netrsacryptoapi

How to extract public key from a .Net DLL in C#?


I want to extract public key, not public key token, in C# from a autenticode signed .Net DLL?


Solution

  • To get a public key from an Autenticode signed .Net library use the following code:

    Assembly assembly = Assembly.LoadFrom("dll_file_name");
    X509Certificate certificate = assembly.ManifestModule.GetSignerCertificate();
    
    byte[] publicKey = certificate.GetPublicKey();
    

    But this will work only if the certificate was installed into Trusted Root Certification Authorities. Otherwise, GetSignerCertificate() returns null.

    The second way allows to get a certificate even if it isn't in Trusted Root Certification Authorities.

    X509Certificate executingCert = X509Certificate.CreateFromSignedFile("dll_file_name");
    byte[] publicKey = certificate.GetPublicKey();