How to Generate Strong Names for an Assembly


There are different ways of signing an assembly. In this article we will explain how to sign an assembly in Visual Studio Developer Environment.

Signing Assembly using Attributes

 

      Developer command prompt showing Key File generation.

 

  1. First create the key file using sn.exe tool as explained. Open Visual Studio Developer Command Prompt.  Change the directory to where you want to store the key. Execute the command sn.exe -k SamplesKeyPair.snk. Key pair file is now stored in the folder command promt is point to.
  2. Open AssemblyInfo.cs file in the Visual Studio Project and update the AssemblyKeyFile attribute by passing the location of the Key file as shown [assembly: AssemblyKeyFile(@"C:\Samples\SamplesKeyPair.snk")]
  3. Compile the project. Now the output assembly of the project is signed.

 

Signing Assembly using Visual Studio Project Properties

 

Signing Assembly  using Visual Studio project properties

 

  1. Go to the properties window of the Visual Studio Project Solution.
  2. Click on Signing Tab.
  3. Check Sign the Assembly check box.
  4. Select new in choose a key file dropdown list box. Enter the Key file name, uncheck protect key file with password and click ok. If you are using an existing key file, select browse in choose key file dropdown list and browse to the file.
  5. Compile the project. Now output of the project is signed.

Delay Signing

Making the key file available to all the developers is not a good practice, access to the key file should be given only to selected persons in the team. When developing strongly named assemblies each assembly referenced by a strongly named assembly must contain public token information, hence public key is required during the development process.

Public key can be extracted from the Key file using the following command

sn -p SamplesKeyPair.snk SamplesKeyPairOnlyPublic.snk

When the above command is run, public key from SampleKeyPair is retrieved and a new key file with only public key is created. We can distribute this file to the developers. This key file, which contains only Public key is enough to generate the public tokens required while adding assembly references. Placeholder for digital signature is created in the partially signed assemblies.

Because the assembly doesn’t have valid signature, verification should be turned off using the below command 

sn –Vr Assembly.dll

Where Assembly.dll is the assembly for which you want to turn off digital signature verification.

Once the development work is finished, signing department can do the actual signing of assemblies by using the below command

sn -R Assembly.dll SampleKeyPair.snk

Where Assembly.dll is the assembly you want to sign and SampleKeyPair.snk is the Key file with both public and private keys.