To sign an assembly with a strong name, you must have a public/private key pair. This cryptographic key pair is used during compilation to create a strong-named assembly. You can generate a key pair using the strong name tool "sn.exe" (e.g. "sn -k newkey.snk"). But there is also a programmatic way to do this shown in the following snippet:
/// <summary>
/// Generating a strong name key pair file programmatically
/// </summary>
/// <param name="fileName">Fullname of the keyfile, which will be generated.</param>
/// <param name="keySize">RSA key size. Default is 1024. Range is 384-16384 in 8 bit increments.</param>
private 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);
}
}
After creating the .snk-file there a three ways to sign an assembly. Via the assembly linker tool "al.exe", via project-properties within visual studio or by using the following attribute in the source code:
[assembly:AssemblyKeyFileAttribute(@"keyfile.snk")]
[assembly:AssemblyDelaySignAttribute(true)]
The latter can be used to turn on/off delay signing the assembly.