如何使用.net库生成强命名的SNK密钥文件 [英] How to generate strong-naming SNK key file with .net libraries

查看:421
本文介绍了如何使用.net库生成强命名的SNK密钥文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的产品需要能够生成.snk文件(系统上未安装Microsoft SDK)。
我可以生成一个有效的SNK文件,但是在指定密码时似乎无法使其正常工作。
谁能给我一些指导吗?
这是我到目前为止所拥有的:

My product needs to be able to generate .snk files (without having Microsoft SDKs installed on the system). I can generate a working SNK file, but I can not seem to get it to work when specifying a password. Can anyone give me some pointers? This is what I have so far:

    internal static void CreateKeyPairFile(string fileName, int keySize, string password)
    {
        if ((keySize % 8) != 0)
        {
            throw new CryptographicException("Invalid key size. Valid size is 384 to 16384 mod 8.  Default 1024.");
        }

        CspParameters parms = new CspParameters();
        parms.KeyNumber = 2;
        if (null != password)
        {
            var passwordString = new System.Security.SecureString();

            foreach (char c in password)
            {
                passwordString.AppendChar(c);
            }
            parms.Flags = CspProviderFlags.UseUserProtectedKey;
            parms.KeyPassword = passwordString;
        }
        RSACryptoServiceProvider provider = new RSACryptoServiceProvider(keySize, parms);

        byte[] array = provider.ExportCspBlob(!provider.PublicOnly);

        using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            fs.Write(array, 0, array.Length);
        }
    }


推荐答案

您使用的 KeyPassword 参数是预期的而不是您尝试使用它的目的。从文档中:

The KeyPassword parameter you use is intended for another purpose than the one you are trying to use it for. From the documentation:


使用KeyPassword属性为智能卡
密钥提供密码。使用此属性指定密码时,不会向用户显示密码
对话框。

Use the KeyPassword property to supply a password for a smart card key. When you specify a password using this property, a password dialog will not be presented to the user.

另请参见回答此问题:简单使用RSACryptoServiceProvider KeyPassword失败

See also the answer to this question: Simple use of RSACryptoServiceProvider KeyPassword fails

除此之外,似乎您不能用密码保护.snk文件。在这种情况下,您可以使用 PKCS#12 文件(.pfx)代替,该文件可以用来对程序集进行签名,也可以使用密码保护。您可以使用 BouncyCastle.NET 之类的库来生成PKCS#12文件。那里有很好的文档说明如何执行此操作,因此在这里我将不做详细介绍。

Besides this, it doesn't seem like you can protect .snk files with a password. What you can do in this case is to use a PKCS#12 file (.pfx) instead which can be used to sign the assemblies and also can be password protected. You can generate a PKCS#12 file using a library such as BouncyCastle.NET. There is good documentation out there on how to do this, so I won't go into detail here.

请参见例如:是否可以仅使用C#以编程方式生成X509证书?

这篇关于如何使用.net库生成强命名的SNK密钥文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆