1. Signing an Assembly
In the last article: Link, we saw how to create Key-Pair and how to store that in a container. Before reading this article, visit the link to know what is a Key File and a Key Container. Now, we will see how to sign an assembly with visual studio 2017 and command prompt. Signing an assembly is useful so that it cannot be modified by unauthorised people. Singing an assembly support deploying it in the GAC and allows versioning policy for the generated binary (Assembly).
2. Command Line – KeyFile & KeyContainer Switches
We can compile a C# dotnet source file in command-line via the CSC (CSharp Compiler) compiler. If the code is written in VB.Net, VBC compiler will do the compilation. During the compilation, we can specify the switch to make use of the key file.
Let us assume the file we want to compile is MySource.cs and Key-Pair is in the MyStrongName.snk file. Now to sign the MySource.cs with the key-pair SNK file, we can use the below command-line which uses the KeyFile switch:
CSC /KeyFile:MyStrongName.snk MySource.cs
Note: While specifying the name, use the path and when the path contains spaces use double quotes. It is also possible to use the Key File in a container while signing an assembly. For example, let us state the Key Container name is KeyConAbc. To sign the assembly using this key container, we can use the below command-line:
CSC /KeyContainer:KeyConAbc MySource.cs
3. Singing Assembly Via Visual Studio IDE
It is also possible to use Visual Studio to generate the Key File or use the existing key file while compiling the project. Now, let us see how to do that. Below is the step-chart (VS 2017 IDE) for Signing An Assembly:
- We have to choose project properties and click on the ‘Signing’ property page.
- Click on the ‘Sign the assembly’ check box. This will enable other control in the section.
- If you already have ‘.snk’ file, you can go for the ‘Browse’ option to pick that file. Here, we click on the ‘New’ option to generate the Strong Name Key (snk) file.
- From the displayed ‘Create Strong Name Key’ dialog, we specify the key file name. Visual studio uses this key file for singing an assembly file or all the files in the project.
- Pick the signing algorithm. This tells how visual studio should generate the private and public key pairs.
- Click OK to dismiss the dialog box.
- Once, we close the dialog box, we will land back to the ‘Singing’ property page and the page display the key file name generated for us (Compare Step 3 in the Steps-Chart).
- Rebuilding the project will sign the assembly with the generated Key file.
- Shows the visual studio generated Strong Name Key file which is singing the assembly as part of the build process.
The command line switches use the already generated Key-File or Key Container for signing the assembly. If we sign the assembly via Visual Studio, the files in the projects are compiled using the generated Strong Name Key file.