Sign a .NET Assembly with a Strong Name Without Recompiling

来源:互联网 发布:linux查网关 编辑:程序博客网 时间:2024/05/22 16:44
Signing a .NET assembly with a strong name is easy in Visual Studio. However, what if this is a 3rd party assembly and you don't have the source?

For me, I have an application that has a requirement that all assemblies are signed with a strong name. One of the assemblies I am using isRestSharp. I like to contribute to RestSharp and I didn't want to modify the project file to sign the assembly as I didn't want that to go back to the repository when I had some changes to contribute.

Not a problem. What I have is a batch file that disassembles the DLL to IL and then reassembles the IL back into a DLL and includes my key file. This way I get to keep the original DLL for projects that I don't need the assembly to have a strong name and a separate one that is signed with the strong name for the projects where I need that.

Here's what I did:
  1. In the Release build folder I created the following:
    • The key file (create using sn.exe -k MyPublicPrivateKeyFile.snk)
    • A subfolder to contain the signed assembly, mine is named "Signed"
    • A batch file (see below)
  2. Create a batch file in the Release folder named "SignAssembly.bat" with the following contents:
del .\Signed\RestSharp.* /F"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\ildasm.exe" .\RestSharp.dll /out:.\Signed\RestSharp.il"C:\Windows\Microsoft.NET\Framework\v2.0.50727\ilasm.exe" .\Signed\RestSharp.il /dll /key=.\RestSharp.snk /output=.\Signed\RestSharp.dllpause
The first line deletes any previously signed assembly. Second line uses ILDASM to disassemble the DLL to IL in the "Signed" folder as RestSharp.il. The third line reassembles the IL into an assembly using ILASM and tells it to use the IL file and the key file. That's it.

Now, whenever I do a new release build, I just run the batch file and I have a signed copy to use, and I did it without changing the project file to do it.