Wednesday, 31 October 2007

Signing a third party assembly

The other day I had to add a library to our third party tools folder (nmock2 actually) but in order to use it in our code I had to ensure that it had a strong name. Now one way I could have done this is to have downloaded the source code for the assembly and then recompiled adding a strong name. However I found a simpler solution on Adrian Hara's blog that showed how I could use the ILMerge tool from MS Research to achieve the same effect but without the hassle (and there would have been) of recompiling the unsigned module.

Essentially what you do is sign your own assembly and merge in the unsigned assembly, creating a single signed assembly package. This does requires some code compilation but not the original code from the unsigned third party assembly, just some of your own. Being a lazy so an so (:-) I decided to automated the process:

  1. Create temporary assembly (ILMerge.dummy.dll) with a correct strong name. This is my favourite bit as the code I'm using to create this assembly doesn't exist (e.g. echo.>tmp.cs) .
  2. Run ILMerge on this assembly together with the third party one, also specifying the strong name.
  3. Delete the temporary assembly

with a command file and that's it.

Here's a batch file snippet that I used to do all of this:

 1: @echo off 


 2: setlocal


 3: echo.>tmp.cs


 4: set thekeyfile="MyStrongNameKeyFile.snk"


 5: csc /out:"ilmerge.dummy.dll" /target:library /keyfile:%thekeyfile% tmp.cs 


 6: if exist "%%~nf.XXXXX%%~xf" del "%%~nf.XXXXX%%~xf"


 7: for %%f in (%1) do "ILMerge.exe" "ilmerge.dummy.%%~nf%%~xf" %%f /ndebug /keyfile:%thekeyfile% /out:%%~nf.XXXXX%%~xf


 8: if exist "ilmerge.dummy.dll" del "ilmerge.dummy.dll"


 9: del tmp.cs


 10: endlocal




By the way the XXXXX is an identifier I've used to distinguish the output from the original assembly (e.g. preet.dll becomes a signed preet.XXXXX.dll). To use it just save the code snippet above use like this:






 1:  


 2: C:\temp\thirdparty>dir /b


 3: MyStrongNameKeyFile.snk


 4: NMock2.dll


 5: signasm.cmd


 6:  


 7: C:\temp\thirdparty>signasm.cmd NMoc*


 8: Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42


 9: for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727


 10: Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.


 11:  


 12:  


 13: C:\temp\thirdparty>dir /b


 14: MyStrongNameKeyFile.snk


 15: NMock2.dll


 16: NMock2.XXXXX.dll


 17: signasm.cmd


 18:  


 19: C:\temp\thirdparty>



1 comment:

Traian said...

congratulations! great post. it helped me alot!