Friday, April 18, 2008

Delay Signing an Assembly

Friday, April 18, 2008 Posted by Andre Broers ,
In this sample I will demonstrate the use of a delay signed assembly.

When an assembly is delay signed, the public key is added to the assembly. Delay signed assemblies can be referenced to even though they are not signed with the private key. This is especially handy while developping because in most circumstances not everyone has access to the final private key. In this blog I will show how this process works.

First the code

helloassembly.cs:

[sourcecode language="CSharp"]

using System;

namespace helloassembly {
public class Hello
{
public string SayHello(string name)
{
return "Hello " + name;
}
}
}

[/sourcecode]

hello.cs:

[sourcecode language="CSharp"]

using System;
using helloassembly;

public class HelloExe
{
[STAThread]
static void Main(string[] args)
{
Hello x = new Hello();
Console.WriteLine(x.SayHello("Andre"));
}
}

[/sourcecode]



create the keypair:
sn -k my.sln

create the public key:
sn -p my.sln mypublic.sln

compile the assembly without signing:
csc /target:library helloassembly.cs

compile the exe:
csc /target:exe /r:helloassembly.dll Hello.cs

run the exe - Works..

sign the helloassembly with key (won't work because it's not a strongly named)
sn -R helloassembly.dll my(public).sln

recompile the helloassembly signed:
csc /target:library /keyfile:my.sln helloassembly.cs

run the hello.exe - Won't work because hello is compiled against a nonsigned assembly

recompile the hello.cs:
csc /target:exe /r:helloassembly.dll Hello.cs

run the hello.exe - Works

resign helloassembly:
sn -R helloassembly.dll my.sln

run the hello.exe - Works

recompile the helloassembly with delay signing:

csc /target:library /keyfile:mypublic.sln /delaysign+ helloassembly.cs

run hello.exe - Fails because the helloassembly is not strong signed.

recompile hello.exe:
csc /target:exe /r:helloassembly.dll Hello.cs
this works because the assembly is delay signed.

run hello.exe - Fails because the helloassembly is not strong signed.

add the helloassembly to the verifications on the local machine:
sn -Vr helloassembly.dll
sn -Vl

run hello.exe - Works because hello.exe is allowed to reference helloassembly

remove the helloassembly
sn -Vu helloassembly.dll
sn -Vl

run hello.exe - Fails as expected

sign the delay signed helloassembly:
sn -R helloassembly.dll my.sln

run hello.exe - Works without recompiling.

I have explained pretty much of the possibilities.

Have fun..