How to generate strong-naming SNK key file with .net libraries

左心房为你撑大大i 提交于 2019-12-14 00:46:04

问题


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);
        }
    }

回答1:


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

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.

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

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.

See for example: Is it possible to programmatically generate an X509 certificate using only C#?



来源:https://stackoverflow.com/questions/6183051/how-to-generate-strong-naming-snk-key-file-with-net-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!