6/09/2006

Protecting "Trial Versions" of assemblies

Recently I saw a post on one of the MS newsgroups looking for a place to store a "File" so that you would be able to read so you'd know if the user of your Trial software was using it beyond the specified trial expiration date.

There were a number of answers, but none of them used the approach that seemed so obvious to me: Why do you need to worry about a file, when you can embed the expiration date directly into the assembly!

Now this is by no means secure, and is certainly not immune from decompilation - not by a long shot. However, it should give those who have any kind of imagination some food for thought. Bear in mind, I'm keeping it very simple, and I haven't even encrypted the expiration date:


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Reflection ;

[assembly: AssemblyConfiguration("06/10/2006")]
// this can be encrypted.
[assembly: AssemblyVersion("1.0.0.0")]
namespace AssemblyConfigurationTest
{
public class WebForm1 : System.Web.UI.Page
{
DateTime ExpirationDate;
private void Page_Load(object sender, System.EventArgs e)
{
//Page.Trace.IsEnabled =true; // you can uncomment this and other lines to see the values without having to be "Debug".
Assembly asm = Assembly.GetExecutingAssembly();
string fullHashString= asm.FullName +asm.GetName().Version.ToString();
Trace.Write(fullHashString);
int asmHash = fullHashString.GetHashCode();
object[] objArray=asm.GetCustomAttributes(false) ;
int hash ;
foreach (object obj in objArray)
{
AssemblyConfigurationAttribute conf =
obj
as AssemblyConfigurationAttribute;
if (conf != null)
{
hash = conf.Configuration.GetHashCode();
//Trace.Write(hash + ": " +asmHash);
if(hash !=-579392602 || asmHash!=-1991291623)
throw new InvalidOperationException("Assembly Has been Altered! Bad, Bad!");
this.ExpirationDate=Convert.ToDateTime(conf.Configuration) ;
}
}
Response.Write("This Trial Version Expires: " +
this.ExpirationDate.ToString());
}