How to generate SNK syntax key file with .net libraries

My product should be able to generate .snk files (without installing the Microsoft SDK on the system). I can generate a working SNK file, but I cannot get it to work when I specify the password. Can someone give me some pointers? This is what I still have:

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); } } 
+7
source share
1 answer

The KeyPassword parameter that you use is for a purpose other than the one for which you are trying to use it. From the documentation:

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

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

Also, it looks like you can protect your .snk files with a password. In this case, you can use the PKCS # 12 file (.pfx), which can be used to sign assemblies, and can also be password protected. You can generate the PKCS # 12 file using a library such as BouncyCastle.NET . There is good documentation on how to do this, so I won’t go into details here.

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

+2
source

All Articles