开发者

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 t开发者_开发问答o 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()


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.


It does not look like Microsoft updated StrongNameKeyPair to support anything other than the snk file format - as there's, sadly, no constructor accepting an RSA instance.

In fact my understanding is that the PKCS#12 support for strongnaming assemblies is an indirect one, i.e. provided by the tools (msbuild or VS.NET) and not directly by the framework.

However you can still programatically sign an assembly using any RSA instance by re-using the (MIT.X11 licensed) code from Mono.Security StrongName class, available in github. It's a bit more work - but it will work on any framework version and any (future) format that gets promoted :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜