How can I add license to my C# desktop application? I need to find a suitable free method to prevent unauthorised users installing my software.
I thought it would be worth adding another answer to this as the accepted answer seems to reference a project that is not currently maintained.
I would recommend looking at Standard.Licensing, which is a free, open-source licensing library for .Net that works with the .Net Framework, Mono, .Net Core, .Net Standard and Xamarin. Is modernises the older Portable.Licensing by adding support for newer platforms, specifically .Net Core and .Net Standard.
Standard.Licensing works by creating a digitally signed XML file that contains information relevant to your product, such as the type of the product and the expiry date. The fact that the XML file has not been changed can be verified when you check the licence and your application can then trust the claims made in the licence file. (Note that you might want to also verify that the computer's clock is accurate to prevent someone just changing the date.)
Standard.Licensing signs the XML file using the Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm, which uses a pair of keys, one public and one private when creating the licence file. You only need to use the public key to decrypt and verify the licence. As it is not possible to use just the public key to modify the licence file, you can just safely include the public with your application and you do not need to resort to approaches such as obfuscating your assembly to prevent people from seeing the public key. Note that this is similar to the approach mentioned in Simon Bridge's answer above.
Standard.Licensing has a fluent API that you use to create and verify the licences. Here's the snippet from their website showing how to create a licence:
var license = License.New()
.WithUniqueIdentifier(Guid.NewGuid())
.As(LicenseType.Trial)
.ExpiresAt(DateTime.Now.AddDays(30))
.WithMaximumUtilization(5)
.WithProductFeatures(new Dictionary
{
{"Sales Module", "yes"},
{"Purchase Module", "yes"},
{"Maximum Transactions", "10000"}
})
.LicensedTo("John Doe", "john.doe@example.com")
.CreateAndSignWithPrivateKey(privateKey, passPhrase);
In your application, you then load and validate the licence file:
using Standard.Licensing.Validation;
var license = License.Load(...);
var validationFailures = license.Validate()
.ExpirationDate()
.When(lic => lic.Type == LicenseType.Trial)
.And()
.Signature(publicKey)
.AssertValidLicense();