Thursday, 29 September 2011

All About Assembly Signing - Public and Private Key

Why? Purpose?

An assembly is signed by a private key within the .snk file during the build process and other assemblies can access it using the public key.

Strong naming gives an assembly a unique identity and provides versioning feature.
1)
To verify that an assembly came from a specified trusted source and have not been modified.
 
For example, you get an assembly from a colleague who says it is from Microsoft. If it's really from Microsoft, the public key that Microsoft has given you will make that assembly usable. Otherwise, if the public key doesn't work, then mean that assembly is not genuinely from Microsoft!

Prevents a malicious user from tampering and modifying an assembly and then re-signing it with the original signer’s key. Simply put, it prevents others to make fake versions of your assemblies.
 
2)
Another purpose is that you have to sign an assembly before it can be installed in the global assembly cache (GAC) where it can be shared by multiple applications.

Tips:
  •  Strong name private key must be kept secure.
  • Strong name public key will be given to the trusted referring assembly.
  • You should always protect your (.snk) file with a password to prevent someone else from using it.
  • One strong name key would be sufficient for all the projects but must be protected dearly!
  • You can’t just upgrade one assembly and deploy. If one assembly needs an upgrade, all the referenced assemblies must also be recompiled and deployed to point to the correct version.
  • The password information is stored in your computer's cryptographic storage database.
4 ways to sign an assembly:
 
To sign an assembly you'd usually need a public/private key pair.
 
  • Using Visual Studio/Project/Proeprties/Signing tab
  • Using AL.exe tool
  • Using AssemblyKeyFile attribute
  • Using AssemblyKeyName attribute
2 ways to create a public/private key pair:
  • Using Visual Studio/Project/Proeprties/Signing tab
  • Using Sn.exe (strong name) tool

How to extract the public key:
 
sn.exe -p KeyPair.snk PublicKey.snk

How to extract the public key token:

sn.exe -tp PublicKey.snk (this displays the public key in a slightly more sensible way!)

Links: