Signing a DLL (Strong Name)
I was working on a project in C# and I had to sign an assembly with a Strong Name.
Here’s how I did that:
- Go to the project’s properties
- Go to the tab
Signing
- Check
Sign the assembly
- Choose
<New...>
from the drop-down list - Give it a name (I used my solution’s name) and uncheck
Protect my key file with a password
The assembly was signed now. However, when I tried to build it, an error occurred:
Assembly generation failed -- Referenced assembly 'Assembly' does not have a strong name
So the DLL had to be signed, too. Luckily, I had the source of the DLL. It’s also possible to sign a DLL without the source, but this won’t always work.
Sign the DLL using the source
- Open the project in
Visual Studio
- Follow the steps to sign an assembly above for the DLL (but now use the key you already created by clicking
<Browse...>
instead of<New...>
) - Build the DLL
If you get the following error:
Friend assembly reference 'Assembly.Tests' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.
Replace the following values in the commands:
Placeholder | Value |
---|---|
{SNK} | The path to the combined key (.snk) |
{PUB} | The path to public key (will be created) |
{KEY} | The public key in SHA1 format |
- Double click the error
- Start Visual Studio’s
Developer Command Prompt
- Issue the following commands:
sn -p "{SNK}" "{PUB}" sn -tp "{PUB}"
- This will display the public key, copy the public key under
Public key (hash algorithm: sha1)
Don’t copy the public key token! - Go back to your project
- Locate the following line:
[assembly: InternalsVisibleTo("Assembly.Tests")]
- Put the public key in the string:
[assembly: InternalsVisibleTo("Assembly.Tests, PublicKey={KEY}")]
- Build the DLL
Sign the DLL without the source
Replace the following values in the commands:
Placeholder | Value |
---|---|
{DLL} | The path to the original DLL |
{IL} | The path to .il file (will be created) |
{RES} | The path to the .res file (located in the same folder as the .il file) |
{KEY} | The path to the .snk file (the key file) |
{DLL2} | The path to the signed DLL (will be created) |
- Start Visual Studio’s
Developer Command Prompt
- Run the following commands:
ildasm "{DLL}" /out:"{IL}" ilasm "{IL}" /res:"{RES}" /dll /key:"{KEY}" /out:"{DLL2}"
The DLL has now been signed with your key. Just re-add the reference to the new, signed DLL in your project and rebuild.
Leave a comment