Published Wednesday, June 21, 2006 7:18 PM by Aleph

Code access protection using Evidence

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 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. 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. This is the piece of code I must put in the constructor:
public class Activator
{
    public Activator()
    {
        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 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;
    }

    //protected methods 

}
So when I call Activator a = new Activator(); if my app is not signed with the same strong name as the Activator.dll the security exception will pop up.


Filed under

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

Name  

Comments 
Type the characters you see in the picture on the left.
    



Note: HTML tags in comment messages are not supported.


About Aleph

VB.NET programmer '02
C# programmer '03
Software Analyst '05
Software Architect '06