Developing licenses in C# - where do I start?

user338195 picture user338195 · May 24, 2010 · Viewed 17.8k times · Source

I'm interested to find out whether there are any standards or resources that you can recommend for developing license models in C#?

Answer

Patrick picture Patrick · May 25, 2010

In C# you can use the Licensing class supplied by Microsoft. A sample is available through the link.

Basically you create a class that inherits from LicenseProvider and type the

[LicenseProvider(typeof(MyControlLicenseProvider))]

as an attribute to your class that you would like to have licensed. In your implementation (MyControlLicenseProvider) you can code the appropriate methods for validating the license to your needs and then have your code call

License license = LicenseManager.Validate(typeof(MyControl), this);

If license is not null your application/control is licensed.

As Sir Graystar states, no system is fool-proof, and someone with the needed skills could engineer themselves around your validation. Don't spend too many hours implementing a rock hard system, but don't make it to easy to circumvent either. :-)

Using a hash like SHA or one of the MD hash functions and feed them some key data could be used to create a simple validation check. Your validation method could do something in the likes of

public override License GetLicense(LicenseContext context,
                                   Type type,
                                   object instance,
                                   bool allowExceptions)
    if (context.UsageMode == LicenseUsageMode.Designtime) {
        // Creating a special DesigntimeLicense will able you to design your
        // control without breaking Visual Studio in the process
        return new DesigntimeLicense();
    }
    byte[] existingSerialKey = getExistingSerial();
    // Algorithm can be SHA1CryptoServiceProvider for instance
    byte[] data = HashAlgorithm.Create().ComputeHash(
        username,
        dateRequested,
        validUntilDate,
        // any other data you would like to validate
    );
    // todo: also check if licensing period is over here. ;-)
    for (int l = 0; l < existingSerialKey.Length; ++l) {
        if (existingSerialKey[i] != data[i]) {
            if (allowExceptions){
                throw new LicenseException(type, instance, "License is invalid");
            }
            return null;
        }
    }
    // RuntimeLicense can be anything inheriting from License
    return new RuntimeLicense();
}

This method returns a custom License, one that for instance has properties regarding the licensing, like a DateTime for the time when licensing runs out. Setting this up should not take to long, it works well with both WinForms and on ASP.NET sites, and will thwart (with no guarantee implied) a simple attempt to break your licensing.