Generating a strong name key pair file programmatically using C-Sharp


using System.Security.Cryptography;
using System.IO;

namespace AssemblyKeyGeneration
{
class GenerateStrongNameKey
{
/// <summary>
/// Generating a strong name key pair file programmatically
/// </summary>
/// <param name=”fileName”>Fullname of the keyfile with full path, which will be generated.</param>
/// <param name=”keySize”>RSA key size. Default is 1024. Range is 384-16384 in 8 bit increments.</param>
public static void CreateKeyPairFile(string fileName, int keySize)
{
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;
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);
}
}
}
}

Advertisements

One thought on “Generating a strong name key pair file programmatically using C-Sharp

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s