Words on my addictions: .NET, Philosophy, Music

3 August 2006

Protect assemblies from unknown callers

Filed under: C# — stefanprodan @ 8:44 pm

If you work with multiple assemblies and you want to make sure no one uses your code by calling methods from other applications you can use strong names, first you have to sign(MSDN How to: Sign an Assembly with Visual Studio) with your private key all your components and application that you deploy to the client. If you want your code to be safe obfuscation is required too, if you have VS.NET 2005 you can use Dotfuscator Community Edition 3.0. So lets suppose I have an assembly that is validating the product serial number at installation time and I want only my application to able to instantiate it.

Code for the assembly you want to protect:

public void Protect() 
    Assembly callerAsm = Assembly.GetCallingAssembly(); 
    StrongName callerSn = GetStrongName(callerAsm.Evidence); 
    Assembly thisAsm = Assembly.GetExecutingAssembly(); 
    StrongName thisSn = GetStrongName(thisAsm.Evidence); 
     if (callerSn == null || thisSn == null || 
          callerSn.PublicKey.ToString() != thisSn.PublicKey.ToString()) 
        throw new System.Security.SecurityException("Unauthorized execution detected, caller assemby unknown."); 

private static StrongName GetStrongName(Evidence evidence) 
    foreach (object o in evidence) 
        if (o is StrongName) 
            return o as StrongName; 
    return null; 

In the assemby on the main class you can call Protect(), if the caller is not signed with your strong name it will raise the Exception.

I hope this will help, drop me if comment if you want.

kick it on DotNetKicks.com


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: