开发者

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

开发者 https://www.devze.com 2023-03-09 03:50 出处:网络
My product needs to be able to generate .snk files (without having Microsoft SDKs installed on the system).

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 gi开发者_开发百科ve 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);
        }
    }


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#?

0

精彩评论

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