Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use StrongNameKeyPair with a password protected keyfile (pfx)?

I am trying to programatically sign an assembly using a password protected keyfile (pfx). However when I try to use the StrongNameKeyPair I get the following exception.

Unable to obtain public key for StrongNameKeyPair. at System.Reflection.StrongNameKeyPair.ComputePublicKey() at System.Reflection.StrongNameKeyPair.get_PublicKey()

like image 674
Simon Avatar asked Sep 26 '11 14:09

Simon


1 Answers

Here is a piece of C# code that creates a StrongNameKeyPair object from a password-protected .PFX file:

    public static StrongNameKeyPair GetStrongNameKeyPairFromPfx(string pfxFile, string password)
    {
        X509Certificate2Collection certs = new X509Certificate2Collection();
        certs.Import(pfxFile, password, X509KeyStorageFlags.Exportable);
        if (certs.Count == 0)
            throw new ArgumentException(null, "pfxFile");

        RSACryptoServiceProvider provider = certs[0].PrivateKey as RSACryptoServiceProvider;
        if (provider == null) // not a good pfx file
            throw new ArgumentException(null, "pfxFile");

        return new StrongNameKeyPair(provider.ExportCspBlob(false));
    }

NOTE: I assume the PFX here has been created by the .NET Framework tools (for example the Visual Studio Strong Name UI form) to support an assembly strong name creation. It may not be ok with any PFX.

like image 67
Simon Mourier Avatar answered Oct 13 '22 02:10

Simon Mourier