Obfusticating License key which is hardcoded - c#

Im using some 3rd party Dll's in my code which require a license key to work.
The license key needs to be passed into the methods when called or they don't work.
However I have written my code in C# which means this license key can be retrieved by decompiling my code.
Is there any way for this license string to be prevented from being decompiled?

(adding as an answer because the message is too long for a comment)
There is no way to completely block access to this string, you can only make it harder. Even if you encrypt it, your program will need the ability to decrypt it, which means that anyone skilled enough can access and reuse the decryption mechanism to get the key in clear format. Or they could even simply read the decrypted key from memory.

You could store the License key in app.config and then encrypt it: http://www.codeproject.com/Articles/18209/Encrypting-the-app-config-File-for-Windows-Forms-A
That probably gets you the most bang for the least buck.

Don't worry too much about it. If your application has access to the key then anyone with access to the binaries and enough time can get that key.
Keep in mind is not your licensing scheme which is at risk, is the licensing scheme of the 3rd party one and thus you have to rely on the applicable laws. If someone decompiles your application and gets access to the key they're breaking the law and it's something you can't prevent.
Your app has the legal rights to use that third library, breaking it has to be handled by law, not by protection, and it's a violation by the terms of the 3rd party licensing scheme. You can go into a certain length to protect it but in the end the responsibility is not yours as there's no way the data can be completely protected (your app needs to know that key and so, at some point, that key will be available in plain text for anyone with access to the code to pick on it). That is true even if the app was entirely written in assembly language.

Add strong verbiage to your license agreement against de-compiling and/or using any licenses that you have acquired in their own software. Require users to electronically accept these terms. Record the timestamp and IP address of each user that accepts these terms on your own server.
If you wanted to add some basic obfuscation in addition to this, that it ok too. But the main point is that as a licensed re-distributor of this component, you are making a concerted effort to prevent others from using your key.

Here's something simple without encryption, to stop a plain-text view of the license:
Store the string in your code and do some replacing before using it, for example:
string LicenseCode = "croftycot";
// Use license code
CallUsingLicense(LicenseCode.Replace("o","a")); // Change to real code: craftycat
You can get more complicated if you need with a regular expressions, mixing a few strings together etc.

Related

How to secure the Software license (Algorithm) [duplicate]

I'm currently involved in developing a product (developed in C#) that'll be available for downloading and installing for free but in a very limited version. To get access to all the features the user has to pay a license fee and receive a key. That key will then be entered into the application to "unlock" the full version.
As using a license key like that is kind of usual I'm wondering :
How's that usually solved?
How can I generate the key and how can it be validated by the application?
How can I also avoid having a key getting published on the Internet and used by others that haven't paid the license (a key that basically isn't "theirs").
I guess I should also tie the key to the version of application somehow so it'll be possible to charge for new keys in feature versions.
Anything else I should think about in this scenario?
Caveat: you can't prevent users from pirating, but only make it easier for honest users to do the right thing.
Assuming you don't want to do a special build for each user, then:
Generate yourself a secret key for the product
Take the user's name
Concatentate the users name and the secret key and hash with (for example) SHA1
Unpack the SHA1 hash as an alphanumeric string. This is the individual user's "Product Key"
Within the program, do the same hash, and compare with the product key. If equal, OK.
But, I repeat: this won't prevent piracy
I have recently read that this approach is not cryptographically very sound. But this solution is already weak (as the software itself has to include the secret key somewhere), so I don't think this discovery invalidates the solution as far as it goes.
Just thought I really ought to mention this, though; if you're planning to derive something else from this, beware.
There are many ways to generate license keys, but very few of those ways are truly secure. And it's a pity, because for companies, license keys have almost the same value as real cash.
Ideally, you would want your license keys to have the following properties:
Only your company should be able to generate license keys for your products, even if someone completely reverse engineers your products (which WILL happen, I speak from experience). Obfuscating the algorithm or hiding an encryption key within your software is really out of the question if you are serious about controlling licensing. If your product is successful, someone will make a key generator in a matter of days from release.
A license key should be useable on only one computer (or at least you should be able to control this very tightly)
A license key should be short and easy to type or dictate over the phone. You don't want every customer calling the technical support because they don't understand if the key contains a "l" or a "1". Your support department would thank you for this, and you will have lower costs in this area.
So how do you solve these challenges ?
The answer is simple but technically challenging: digital signatures using public key cryptography. Your license keys should be in fact signed "documents", containing some useful data, signed with your company's private key. The signatures should be part of the license key. The product should validate the license keys with the corresponding public key. This way, even if someone has full access to your product's logic, they cannot generate license keys because they don't have the private key. A license key would look like this: BASE32(CONCAT(DATA, PRIVATE_KEY_ENCRYPTED(HASH(DATA))))
The biggest challenge here is that the classical public key algorithms have large signature sizes. RSA512 has an 1024-bit signature. You don't want your license keys to have hundreds of characters.
One of the most powerful approaches is to use elliptic curve cryptography (with careful implementations to avoid the existing patents). ECC keys are like 6 times shorter than RSA keys, for the same strength. You can further reduce the signature sizes using algorithms like the Schnorr digital signature algorithm (patent expired in 2008 - good :) )
This is achievable by product activation (Windows is a good example). Basically, for a customer with a valid license key, you need to generate some "activation data" which is a signed message embedding the computer's hardware id as the signed data. This is usually done over the internet, but only ONCE: the product sends the license key and the computer hardware id to an activation server, and the activation server sends back the signed message (which can also be made short and easy to dictate over the phone). From that moment on, the product does not check the license key at startup, but the activation data, which needs the computer to be the same in order to validate (otherwise, the DATA would be different and the digital signature would not validate). Note that the activation data checking do not require verification over the Internet: it is sufficient to verify the digital signature of the activation data with the public key already embedded in the product.
Well, just eliminate redundant characters like "1", "l", "0", "o" from your keys. Split the license key string into groups of characters.
Simple answer - No matter what scheme you use it can be cracked.
Don't punish honest customers with a system meant to prevent hackers, as hackers will crack it regardless.
A simple hashed code tied to their email or similar is probably good enough. Hardware based IDs always become an issue when people need to reinstall or update hardware.
Good thread on the issue:
http://discuss.joelonsoftware.com/default.asp?biz.5.82298.34
When generating the key, don't forget to concatenate the version and build number to the string you calculate the hash on. That way there won't be a single key that unlocks all everything you ever released.
After you find some keys or patches floating in astalavista.box.sk you'll know that you succeeded in making something popular enough that somebody bothered to crack. Rejoice!
I'm one of the developers behind the Cryptolens software licensing platform and have been working on licensing systems since the age of 14. In this answer, I have included some tips based on experience acquired over the years.
The best way of solving this is by setting up a license key server that each instance of the application will call in order to verify a license key.
Benefits of a license key server
The advantages with a license key server is that:
you can always update or block a license key with immediate effect.
each license key can be locked to certain number of machines (this helps to prevent users from publishing the license key online for others to use).
Considerations
Although verifying licenses online gives you more control over each instance of the application, internet connection is not always present (especially if you target larger enterprises), so we need another way of performing the license key verification.
The solution is to always sign the license key response from the server using a public-key cryptosystem such as RSA or ECC (possibly better if you plan to run on embedded systems). Your application should only have the public key to verify the license key response.
So in case there's no internet connection, you can use the previous license key response instead. Make sure to store both the date and the machine identifier in the response and check that it's not too old (eg. you allow users to be offline at most 30 days, etc) and that the license key response belongs to the correct device.
Note you should always check the certificate of license key response, even if you are connected to the internet), in order to ensure that it has not been changed since it left the server (this still has to be done even if your API to the license key server uses https)
Protecting secret algorithms
Most .NET applications can be reverse engineered quite easily (there is both a diassembler provided by Microsoft to get the IL code and some commercial products can even retrieve the source code in eg. C#). Of course, you can always obfuscate the code, but it's never 100% secure.
I most cases, the purpose of any software licensing solution is to help honest people being honest (i.e. that honest users who are willing to pay don't forget to pay after a trial expires, etc).
However, you may still have some code that you by no means want to leak out to the public (eg. an algorithm to predict stock prices, etc). In this case, the only way to go is to create an API endpoint that your application will call each time the method should be executed. It requires internet connection but it ensures that your secret code is never executed by the client machine.
Implementation
If you don't want to implement everything yourself, I would recommend to take a look at this tutorial (part of Cryptolens)
Besides what has already been stated....
Any use of .NET applications are inherently breakable because of the intermediate language issues. A simple disassembly of the .NET code will open your product to anyone. They can easily bypass your licensing code at that point.
You can't even use hardware values to create a key anymore. Virtual machines now allow someone to create an image of a 'licensed' machine and run it on any platform they choose.
If it's expensive software there are other solutions. If it's not, just make it difficult enough for the casual hacker. And accept the fact that there will be unlicensed copies out there eventually.
If your product is complicated, the inherent support issues will be create some protection for you.
The C# / .NET engine we use for licence key generation is now maintained as open source:
https://github.com/appsoftware/.NET-Licence-Key-Generator.
It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.
As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.
I've used Crypkey in the past. It's one of many available.
You can only protect software up to a point with any licensing scheme.
I don't know how elaborate you want to get
but i believe that .net can access the hard drive serial number.
you could have the program send you that and something eles ( like user name and mac address of the nic)
you compute a code based off that and email them back the key.
they will keep them from switching machines after they have the key.
I strongly believe, that only public key cryptography based licensing system is the right approach here, because you don't have to include essential information required for license generation into your sourcecode.
In the past, I've used Treek's Licensing Library many times, because it fullfills this requirements and offers really good price. It uses the same license protection for end users and itself and noone cracked that until now. You can also find good tips on the website to avoid piracy and cracking.
The only way to do everything you asked for is to require an internet access and verification with a server. The application needs to sign in to the server with the key, and then you need to store the session details, like the IP address. This will prevent the key from being used on several different machines. This is usually not very popular with the users of the application, and unless this is a very expensive and complicated application it's not worth it.
You could just have a license key for the application, and then check client side if the key is good, but it is easy to distribute this key to other users, and with a decompiler new keys can be generated.
I've implemented internet-based one-time activation on my company's software (C# .net) that requires a license key that refers to a license stored in the server's database. The software hits the server with the key and is given license information that is then encrypted locally using an RSA key generated from some variables (a combination of CPUID and other stuff that won't change often) on the client computer and then stores it in the registry.
It requires some server-side coding, but it has worked really well for us and I was able to use the same system when we expanded to browser-based software. It also gives your sales people great info about who, where and when the software is being used. Any licensing system that is only handled locally is fully vulnerable to exploitation, especially with reflection in .NET. But, like everyone else has said, no system is wholly secure.
In my opinion, if you aren't using web-based licensing, there's no real point to protecting the software at all. With the headache that DRM can cause, it's not fair to the users who have actually paid for it to suffer.
You can use a free third party solution to handle this for you such as Quantum-Key.Net It's free and handles payments via paypal through a web sales page it creates for you, key issuing via email and locks key use to a specific computer to prevent piracy.
Your should also take care to obfuscate/encrypt your code or it can easily be reverse engineered using software such as De4dot and .NetReflector. A good free code obfuscator is ConfuserEx wich is fast and simple to use and more effective than expensive alternatives.
You should run your finished software through De4Dot and .NetReflector to reverse-engineer it and see what a cracker would see if they did the same thing and to make sure you have not left any important code exposed or undisguised.
Your software will still be crackable but for the casual cracker it may well be enough to put them off and these simple steps will also prevent your code being extracted and re-used.
https://quantum-key.net
How to use ConfuserEx?
https://github.com/0xd4d/de4dot
https://www.red-gate.com/dynamic/products/dotnet-development/reflector/download
I know this is an old question, but I referenced this when I was re-writing my licensing process for one of my applications.
After reading a lot of opinions out there and relying on past experience with license codes I came up with this process.
public static class LicenseGenerator
{
private static string validChars = "ACEFHJKMNPRSTUVWXYZ234579";
private static Random rnd = new Random(Guid.NewGuid().GetHashCode());
/// <summary>
/// Generate a license code
/// </summary>
/// <param name="length">length of each phrase</param>
/// <param name="number">number of phrases separated by a '-'</param>
/// <returns></returns>
public static string GetNewCode(int length, int number)
{
string license = string.Empty;
for (int numberOfPhrases = 0; numberOfPhrases < number; numberOfPhrases++)
{
license += getPhrase(length);
if (numberOfPhrases < number)
license += "-";
}
return license.TrimEnd('-');
}
/// <summary>
/// generate a phrase
/// </summary>
/// <param name="length">length of phrase</param>
/// <returns></returns>
private static string getPhrase(int length)
{
string phrase = string.Empty;
for (int loop = 0; loop < length; loop++)
{
phrase += validChars[rnd.Next(validChars.Length)];
}
return phrase;
}
}
You really don't want to provide a code that has similar letters; it makes for a mess when the end user goes to enter it in. Letters like 6 and G, B and 8, L, I, and 1. Of course if you do want them, you can always add them back in... The above code will generate a license like xxxx-xxxx-xxxx-xxxx using the characters in "validChars". Calling GetNewCode(4, 4) will return a code like above.
I'm using Azure functions to register then validate the code. When my app registers the code, it generates an encrypted hash with things that are unique to the install, device and/or user. That is provided to the registration function and is stored with the key in the DB in Azure.
The validate regenerates the key and provides it with the license code, IP address (which in my case will not change and if it does then it will need to be updated anyway), and the regenerated hash then the Azure function returns if the application is licensed. I do store a "temporary" key on their server that allows the app to run for a period of time without talking back up.
Of course, my app must be on the net for it to work regardless.
So, the end result is a simple key for the end user to type in and an easy process to manage the license on the backend. I can also invalidate a license if need be.
I solved it by interfacing my program with a discord server, where it checks in a specific chat if the product key entered by the user exists and is still valid. In this way to receive a product key the user would be forced to hack discord and it is very difficult.

Could I hide the encryption key of a c# exe securely (in a way that can't be decompiled in any known way), as in C/C++?

I love c# for programming applications (I consider myself intermediate with c#, and a bit less with C/C++, but am only learning, nothing real yet in the arena), and I used to like it until i discovered "anyone" who understand MSIL (not an easy task to learn neither) could decompile my code. I don’t really care about someone decompiling my code, but my utter concern is the security for my eventual program users. I know obfuscators exist, and I even know of one or two that are really good, I hear (even if they only delay a decompiling).
For example, if I want to decrypt something using c#, some where in the code the key should be, making it a danger for anyone who use my program (someone who know someone who encrypted the file using my program could decrypt it by researching on my MSIL code, finding my key). Then, the developing of massive applications that encrypt/decrypt stuff (or OpenSSL) is insane with c#, I think, for this reason.
I mean, most users won’t know what language was used to make that exe, but a bunch of people are able to program n c#, and an elite of this people can read MSIL, and a minority of this elite would like to hack what ever is possible to hack. Of those people who like to hack, some of them can do it with perverse intentions (in a value-less world where we live that shouldn’t surprise anyone).
So, if I want to make a program that download a file from the internet, someone could interfere the transmission and do some evil, even if I use OpenSSL with c#, because somewhere in the c# file is the key. I know avoiding hacking is probably impossible, but it looks like c# is a very unsecure way.
Does it happen with Java? (Java has the same “interpreting” and “decompile” structure as C#); I mean, the fact that the key is visible in Java (with some educated eye) some where in the building file? Or does Java use some C/C++ based API that makes it harder (way harder) to decompile the file where the key is and so making it hard to get the key?
Is my only option to write my program with c/c++? Because if so, my only option is C++Builder, since its a hell to even try to watch (and less to learn) MFC/OWL code; I mean: I cant hardly think of someone who could like MFC/OWL programming. In fact, I suppose Assembly could be of more interest in the today programming world.
So, here I am, wanting to find someone who could explain me better a way to store securely crypto keys for encrypting/decrypting or to use OpenSSL with c#. Or even with Java. I would like to confirm that C/C++ is the only way of really using these features with some security for decompiling reasons (as other compiled programming languages, i.e. Delphi).
If anyone knows a site where I can find precise information about the subtle reasoning I suppose I have done (specially one that shows am wrong in my analysis), please tell me. If any one can confirm my analysis, please confirm. If anyone find any hole in my analysis, again, please tell me, and where to find more information that rule me to get a better understanding of all this.
Am sorry for making this philosophical computer programming question that long.
Thank you,
McNaddy
Could I hide the encryption key of a c# exe securely (in a way that can't be decompiled in any known way), as in C/C++?
No. You can't do that in any language.
The .NET security system is designed to protect benign users from hostile code. You are trying to protect benign code from hostile users. You simply cannot do that, so don't even try. If you have a secret, do not share it with anyone.
The purpose of crypto is to leverage the secrecy of some private key into the secrecy of a text. If that is not the security problem you face, crypto is the wrong tool. Explain the security problem you actually have and someone here can help you solve it.
So, if I want to make a program that download a file from the internet, someone could interfere the transmission and do some evil, even if I use OpenSSL with c#, because somewhere in the c# file is the key.
You don't need to store a secret key in the program just to download a file safely.
If you want to ensure that the file you downloaded is authentic and hasn't been modified in transit, you use a digital signature. The private key used to make the signature doesn't have to be (and shouldn't be) distributed with the program; all the program needs is the corresponding public key, which you don't have to hide.
If you want to prevent eavesdroppers from reading the file as it's downloaded, then you need to encrypt it, but that can be done with a temporary session key generated randomly for each download; it doesn't have to be stored anywhere. If you use HTTPS for your download, it'll do this for you.
The choice you've mentioned (embed key into executable) is bad irrespective of language you choose - it is not too hard to extract data from C/C++ and slightly easier for C#/Java.
As Jordão said - you need to figure out your story of distributing key outside the binaries. You also need to figure out what you actually trying to protect and understand possible exploits. Just using encryption of some sort in an application does not make it more secure.
You should not store cryptographic keys inside assemblies; they should normally be provided from outside, e.g. from a key-store, or derived from a secret known to a user.
You can also generate a key from a password(this means the key is no more stronger than the password though). So each time the user runs the program, they are prompted for a password, and that password is then used to generate a key. Depending on your requirements you could employ this in a variety of ways.
When the user needs to access the encrypted data, the password can be provided again and this generates the key for use during that session. Once the program is closed the key is discarded(there are techniques/APIs in C# to help ensure that sensitive data is only present in memory as short a time as possible).
For example, this is essentially what many password storing programs like Keepass or Roboform do. The user can upload and download the encrypted data to and from servers. No keys are ever stores, and instead generated on demand as the user supplies their password for that session.
With a service like Dropbox, when you register with their site, they generate the private key on their server and keep a copy there. So the user's machine and client software never store the key, but the server has a copy stored. Dropbox does this so that they can decrypt user data for many purposes, such as compression, de-duplication, compliance with law enforcement, etc.

Protecting XML file from editing

We have around 60 MB of device configuration implemented in at least 1000 xml files.
Now we are releasing the software to the customers. But our requirement is not to allow the user to view and edit the xml configuration files. XML configuration files contains a lot of secret of the device information which can be easily hacked if it is readable.
Now we need to encrypt the xml files. Are there any recommended method to encrypt the xml file and it can be decrypted at run time?
This is a problem known from DRM applications - you want to make the data available to the user agent of your choice but not to the user operating the user agent. But, since the user agent is usually on the user's side, as Jon and Oded point out, a determined hacker will find a way to break the encryption. It's a cat and mouse game. You are trying to find a solution to exactly the same problem that people implementing DRM want to solve. Software-only user agents are easier to hack than hardware-assisted user agents, but in either case time works for the hackers. The latest development is the latter - embedding all the cryptography in hardware - like the HDMI's HDCP method (High-bandwith Digital Content protection Path) where they have essentially made the decrypted digital signal inaccessible to the user by letting it pass along black-box hardware from its point of decryption until it is made so available, but at the intended destination - TV screen. The key for HDCP to succeed however was implementing it in hardware. Most hackers have learned to deal with software. But since I would say there is 1 good hardware hacker per 100 good software hackers these days, the mouse hopes no cat will be around to catch it. Sorry for too much theory, it is essential to your problem though, I believe. If you are still willing to play the game, encrypt your XML files and make sure the decryption key is not available to potential hackers on a silver plate - i.e. obfuscate it, can't do much else.
How determined are you expecting the "hackers" to be? If all the information required to decrypt the information has to be present on the system anyway, then a determined attacker is going to be able to get at it anyway.
You can use the classes in the Cryptography namespace.
Most of the encryption classes will allow you to encrypt and decrypt streams, so are good for your purpose.
However, you will still need to hold the encryption keys somewhere, even if it is in the assembly.
As Jon points out, a determined hacker will find a way to break any encryption.
As others explained, you won't get it absolutely secure without a trusted device which stores the key and does the decryption without granting access to the key under any circumstances. Computers aren't "trusted devices"...
My employer sells such technology and if your data is really money worth, you should possibly take such a solution into account.
If an additional USB-Dongle is not acceptable (or too expensive) at least use public-key (asymmetic) cryptography (see System.Security.Cryptography).
Asymmetric cryptography has the advantage that the key used to decrypt your data can't be used to encrypt the data.
Your application has to store the decryption key and the hacker can determine it with more or less effort. He then can decrypt all your data but he can't not encrpyt the changed data again. So he can't use your application with the changed data.
If you want to prevent him from doing this, you have to obfuscate your application and use anti-debugging techniques (static and runtime). If you go this way buying an existing solution is probably cheaper.
Watch out: Hackers can see all functions in .net generated executables and dll's!
If you make a decription algorithm in your .net project like DecryptXML(string Path), it is very easy for a hacker to call this instruction. So be sure to dotfuscate your project.

How can I create a product key for my C# application?

How can I create a product key for my C# Application?
I need to create a product (or license) key that I update annually. Additionally I need to create one for trial versions.
Related:
How do I best obfuscate my C# product license verification code?
How do you protect your software from illegal distribution?
You can do something like create a record which contains the data you want to authenticate to the application. This could include anything you want - e.g. program features to enable, expiry date, name of the user (if you want to bind it to a user). Then encrypt that using some crypto algorithm with a fixed key or hash it. Then you just verify it within your program. One way to distribute the license file (on windows) is to provide it as a file which updates the registry (saves the user having to type it).
Beware of false sense of security though - sooner or later someone will simply patch your program to skip that check, and distribute the patched version. Or, they will work out a key that passes all checks and distribute that, or backdate the clock, etc. It doesn't matter how convoluted you make your scheme, anything you do for this will ultimately be security through obscurity and they will always be able to this. Even if they can't someone will, and will distribute the hacked version. Same applies even if you supply a dongle - if someone wants to, they can patch out the check for that too. Digitally signing your code won't help, they can remove that signature, or resign it.
You can complicate matters a bit by using techniques to prevent the program running in a debugger etc, but even this is not bullet proof. So you should just make it difficult enough that an honest user will not forget to pay. Also be very careful that your scheme does not become obtrusive to paying users - it's better to have some ripped off copies than for your paying customers not to be able to use what they have paid for.
Another option is to have an online check - just provide the user with a unique ID, and check online as to what capabilities that ID should have, and cache it for some period. All the same caveats apply though - people can get round anything like this.
Consider also the support costs of having to deal with users who have forgotten their key, etc.
edit: I just want to add, don't invest too much time in this or think that somehow your convoluted scheme will be different and uncrackable. It won't, and cannot be as long as people control the hardware and OS your program runs on. Developers have been trying to come up with ever more complex schemes for this, thinking that if they develop their own system for it then it will be known only to them and therefore 'more secure'. But it really is the programming equivalent of trying to build a perpetual motion machine. :-)
Who do you trust?
I've always considered this area too critical to trust a third party to manage the runtime security of your application. Once that component is cracked for one application, it's cracked for all applications. It happened to Discreet in five minutes once they went with a third-party license solution for 3ds Max years ago... Good times!
Seriously, consider rolling your own for having complete control over your algorithm. If you do, consider using components in your key along the lines of:
License Name - the name of client (if any) you're licensing. Useful for managing company deployments - make them feel special to have a "personalised" name in the license information you supply them.
Date of license expiry
Number of users to run under the same license. This assumes you have a way of tracking running instances across a site, in a server-ish way
Feature codes - to let you use the same licensing system across multiple features, and across multiple products. Of course if it's cracked for one product it's cracked for all.
Then checksum the hell out of them and add whatever (reversable) encryption you want to it to make it harder to crack.
To make a trial license key, simply have set values for the above values that translate as "trial mode".
And since this is now probably the most important code in your application/company, on top of/instead of obfuscation consider putting the decrypt routines in a native DLL file and simply P/Invoke to it.
Several companies I've worked for have adopted generalised approaches for this with great success. Or maybe the products weren't worth cracking ;)
If you are asking about the keys that you can type in, like Windows product keys, then they are based on some checks. If you are talking about the keys that you have to copy paste, then they are based on a digitial signature (private key encryption).
A simple product key logic could be to start with saying that the product key consists of four 5-digit groups, like abcde-fghij-kljmo-pqrst, and then go on to specify internal relationships like f+k+p should equal a, meaning the first digits of the 2, 3 and 4 group should total to a. This means that 8xxxx-2xxxx-4xxxx-2xxxx is valid, so is 8xxxx-1xxxx-0xxxx-7xxxx. Of course, there would be other relationships as well, including complex relations like, if the second digit of the first group is odd, then the last digit of the last group should be odd too. This way there would be generators for product keys and verification of product keys would simply check if it matches all the rules.
Encryption are normally the string of information about the license encrypted using a private key (== digitally signed) and converted to Base64. The public key is distributed with the application. When the Base64 string arrives, it is verified (==decrypted) by the public key and if found valid, the product is activated.
Whether it's trivial or hard to crack, I'm not sure that it really makes much of a difference.
The likelihood of your app being cracked is far more proportional to its usefulness rather than the strength of the product key handling.
Personally, I think there are two classes of user. Those who pay. Those who don't. The ones that do will likely do so with even the most trivial protection. Those who don't will wait for a crack or look elsewhere. Either way, it won't get you any more money.
I have to admit I'd do something rather insane.
Find a CPU bottleneck and extract it to a P/Invokeable DLL file.
As a post build action, encrypt part of the DLL file with an XOR
encryption key.
Select a public/private key scheme, include public key in the DLL file
Arrange so that decrypting the product key and XORing the two
halves together results in the encryption key for the DLL.
In the DLL's DllMain code, disable protection (PAGE_EXECUTE_READWRITE)
and decrypt it with the key.
Make a LicenseCheck() method that makes a sanity check of the
license key and parameters, then checksums entire DLL file, throwing
license violation on either. Oh, and do some other initialization
here.
When they find and remove the LicenseCheck, what fun will follow
when the DLL starts segmentation faulting.
There is the option Microsoft Software Licensing and Protection (SLP) Services as well. After reading about it I really wish I could use it.
I really like the idea of blocking parts of code based on the license. Hot stuff, and the most secure for .NET. Interesting read even if you don't use it!
Microsoft® Software Licensing and
Protection (SLP) Services is a
software activation service that
enables independent software vendors
(ISVs) to adopt flexible licensing
terms for their customers. Microsoft
SLP Services employs a unique
protection method that helps safeguard
your application and licensing
information allowing you to get to
market faster while increasing
customer compliance.
Note: This is the only way I would release a product with sensitive code (such as a valuable algorithm).
If you want a simple solution just to create and verify serial numbers, try Ellipter. It uses elliptic curves cryptography and has an "Expiration Date" feature so you can create trial verisons or time-limited registration keys.
Another good inexpensive tool for product keys and activations is a product called InstallKey. Take a look at www.lomacons.com
One simple method is using a Globally Unique Identifier (GUID). GUIDs are usually stored as 128-bit values and are commonly displayed as 32 hexadecimal digits with groups separated by hyphens, such as {21EC2020-3AEA-4069-A2DD-08002B30309D}.
Use the following code in C# by System.Guid.NewGuid().
getKey = System.Guid.NewGuid().ToString().Substring(0, 8).ToUpper(); //Will generate a random 8 digit hexadecimal string.
_key = Convert.ToString(Regex.Replace(getKey, ".{4}", "$0/")); // And use this to separate every four digits with a "/".
I hope it helps.
The trick is to have an algorithm that only you know (such that it could be decoded at the other end).
There are simple things like, "Pick a prime number and add a magic number to it"
More convoluted options such as using asymmetric encryption of a set of binary data (that could include a unique identifier, version numbers, etc) and distribute the encrypted data as the key.
Might also be worth reading the responses to this question as well
There are some tools and API's available for it. However, I do not think you'll find one for free ;)
There is for instance the OLicense suite:
http://www.olicense.de/index.php?lang=en
Please check this answer: https://stackoverflow.com/a/38598174/1275924
The idea is to use Cryptolens as the license server. Here's a step-by-step example (in C# and VB.NET). I've also attached a code snippet for key verification below (in C#):
var licenseKey = "GEBNC-WZZJD-VJIHG-GCMVD";
var RSAPubKey = "{enter the RSA Public key here}";
var auth = "{access token with permission to access the activate method}";
var result = Key.Activate(token: auth, parameters: new ActivateModel()
{
Key = licenseKey,
ProductId = 3349,
Sign = true,
MachineCode = Helpers.GetMachineCode()
});
if (result == null || result.Result == ResultType.Error ||
!result.LicenseKey.HasValidSignature(RSAPubKey).IsValid())
{
// an error occurred or the key is invalid or it cannot be activated
// (eg. the limit of activated devices was achieved)
Console.WriteLine("The license does not work.");
}
else
{
// everything went fine if we are here!
Console.WriteLine("The license is valid!");
}
Console.ReadLine();
You can check LicenseSpot. It provides:
Free Licensing Component
Online Activation
API to integrate your app and online store
Serial number generation
Revoke licenses
Subscription Management
I'm going to piggyback a bit on #frankodwyer's great answer and dig a little deeper into online-based licensing. I'm the founder of Keygen, a licensing REST API built for developers.
Since you mentioned wanting 2 "types" of licenses for your application, i.e. a "full version" and a "trial version", we can simplify that and use a feature license model where you license specific features of your application (in this case, there's a "full" feature-set and a "trial" feature-set).
To start off, we could create 2 license types (called policies in Keygen) and whenever a user registers an account you can generate a "trial" license for them to start out (the "trial" license implements our "trial" feature policy), which you can use to do various checks within the app e.g. can user use Trial-Feature-A and Trial-Feature-B.
And building on that, whenever a user purchases your app (whether you're using PayPal, Stripe, etc.), you can generate a license implementing the "full" feature policy and associate it with the user's account. Now within your app you can check if the user has a "full" license that can do Pro-Feature-X and Pro-Feature-Y (by doing something like user.HasLicenseFor(FEATURE_POLICY_ID)).
I mentioned allowing your users to create user accounts—what do I mean by that? I've gone into this in detail in a couple other answers, but a quick rundown as to why I think this is a superior way to authenticate and identify your users:
User accounts let you associate multiple licenses and multiple machines to a single user, giving you insight into your customer's behavior and to prompt them for "in-app purchases" i.e. purchasing your "full" version (kind of like mobile apps).
We shouldn't require our customers to input long license keys, which are both tedious to input and hard to keep track of i.e. they get lost easily. (Try searching "lost license key" on Twitter!)
Customers are accustomed to using an email/password; I think we should do what people are used to doing so that we can provide a good user experience (UX).
Of course, if you don't want to handle user accounts and you want your users to input license keys, that's completely fine (and Keygen supports doing that as well). I'm just offering another way to go about handling that aspect of licensing and hopefully provide a nice UX for your customers.
Finally since you also mentioned that you want to update these licenses annually, you can set a duration on your policies so that "full" licenses will expire after a year and "trial" licenses last say 2 weeks, requiring that your users purchase a new license after expiration.
I could dig in more, getting into associating machines with users and things like that, but I thought I'd try to keep this answer short and focus on simply licensing features to your users.

How to generate and validate a software license key?

I'm currently involved in developing a product (developed in C#) that'll be available for downloading and installing for free but in a very limited version. To get access to all the features the user has to pay a license fee and receive a key. That key will then be entered into the application to "unlock" the full version.
As using a license key like that is kind of usual I'm wondering :
How's that usually solved?
How can I generate the key and how can it be validated by the application?
How can I also avoid having a key getting published on the Internet and used by others that haven't paid the license (a key that basically isn't "theirs").
I guess I should also tie the key to the version of application somehow so it'll be possible to charge for new keys in feature versions.
Anything else I should think about in this scenario?
Caveat: you can't prevent users from pirating, but only make it easier for honest users to do the right thing.
Assuming you don't want to do a special build for each user, then:
Generate yourself a secret key for the product
Take the user's name
Concatentate the users name and the secret key and hash with (for example) SHA1
Unpack the SHA1 hash as an alphanumeric string. This is the individual user's "Product Key"
Within the program, do the same hash, and compare with the product key. If equal, OK.
But, I repeat: this won't prevent piracy
I have recently read that this approach is not cryptographically very sound. But this solution is already weak (as the software itself has to include the secret key somewhere), so I don't think this discovery invalidates the solution as far as it goes.
Just thought I really ought to mention this, though; if you're planning to derive something else from this, beware.
There are many ways to generate license keys, but very few of those ways are truly secure. And it's a pity, because for companies, license keys have almost the same value as real cash.
Ideally, you would want your license keys to have the following properties:
Only your company should be able to generate license keys for your products, even if someone completely reverse engineers your products (which WILL happen, I speak from experience). Obfuscating the algorithm or hiding an encryption key within your software is really out of the question if you are serious about controlling licensing. If your product is successful, someone will make a key generator in a matter of days from release.
A license key should be useable on only one computer (or at least you should be able to control this very tightly)
A license key should be short and easy to type or dictate over the phone. You don't want every customer calling the technical support because they don't understand if the key contains a "l" or a "1". Your support department would thank you for this, and you will have lower costs in this area.
So how do you solve these challenges ?
The answer is simple but technically challenging: digital signatures using public key cryptography. Your license keys should be in fact signed "documents", containing some useful data, signed with your company's private key. The signatures should be part of the license key. The product should validate the license keys with the corresponding public key. This way, even if someone has full access to your product's logic, they cannot generate license keys because they don't have the private key. A license key would look like this: BASE32(CONCAT(DATA, PRIVATE_KEY_ENCRYPTED(HASH(DATA))))
The biggest challenge here is that the classical public key algorithms have large signature sizes. RSA512 has an 1024-bit signature. You don't want your license keys to have hundreds of characters.
One of the most powerful approaches is to use elliptic curve cryptography (with careful implementations to avoid the existing patents). ECC keys are like 6 times shorter than RSA keys, for the same strength. You can further reduce the signature sizes using algorithms like the Schnorr digital signature algorithm (patent expired in 2008 - good :) )
This is achievable by product activation (Windows is a good example). Basically, for a customer with a valid license key, you need to generate some "activation data" which is a signed message embedding the computer's hardware id as the signed data. This is usually done over the internet, but only ONCE: the product sends the license key and the computer hardware id to an activation server, and the activation server sends back the signed message (which can also be made short and easy to dictate over the phone). From that moment on, the product does not check the license key at startup, but the activation data, which needs the computer to be the same in order to validate (otherwise, the DATA would be different and the digital signature would not validate). Note that the activation data checking do not require verification over the Internet: it is sufficient to verify the digital signature of the activation data with the public key already embedded in the product.
Well, just eliminate redundant characters like "1", "l", "0", "o" from your keys. Split the license key string into groups of characters.
Simple answer - No matter what scheme you use it can be cracked.
Don't punish honest customers with a system meant to prevent hackers, as hackers will crack it regardless.
A simple hashed code tied to their email or similar is probably good enough. Hardware based IDs always become an issue when people need to reinstall or update hardware.
Good thread on the issue:
http://discuss.joelonsoftware.com/default.asp?biz.5.82298.34
When generating the key, don't forget to concatenate the version and build number to the string you calculate the hash on. That way there won't be a single key that unlocks all everything you ever released.
After you find some keys or patches floating in astalavista.box.sk you'll know that you succeeded in making something popular enough that somebody bothered to crack. Rejoice!
I'm one of the developers behind the Cryptolens software licensing platform and have been working on licensing systems since the age of 14. In this answer, I have included some tips based on experience acquired over the years.
The best way of solving this is by setting up a license key server that each instance of the application will call in order to verify a license key.
Benefits of a license key server
The advantages with a license key server is that:
you can always update or block a license key with immediate effect.
each license key can be locked to certain number of machines (this helps to prevent users from publishing the license key online for others to use).
Considerations
Although verifying licenses online gives you more control over each instance of the application, internet connection is not always present (especially if you target larger enterprises), so we need another way of performing the license key verification.
The solution is to always sign the license key response from the server using a public-key cryptosystem such as RSA or ECC (possibly better if you plan to run on embedded systems). Your application should only have the public key to verify the license key response.
So in case there's no internet connection, you can use the previous license key response instead. Make sure to store both the date and the machine identifier in the response and check that it's not too old (eg. you allow users to be offline at most 30 days, etc) and that the license key response belongs to the correct device.
Note you should always check the certificate of license key response, even if you are connected to the internet), in order to ensure that it has not been changed since it left the server (this still has to be done even if your API to the license key server uses https)
Protecting secret algorithms
Most .NET applications can be reverse engineered quite easily (there is both a diassembler provided by Microsoft to get the IL code and some commercial products can even retrieve the source code in eg. C#). Of course, you can always obfuscate the code, but it's never 100% secure.
I most cases, the purpose of any software licensing solution is to help honest people being honest (i.e. that honest users who are willing to pay don't forget to pay after a trial expires, etc).
However, you may still have some code that you by no means want to leak out to the public (eg. an algorithm to predict stock prices, etc). In this case, the only way to go is to create an API endpoint that your application will call each time the method should be executed. It requires internet connection but it ensures that your secret code is never executed by the client machine.
Implementation
If you don't want to implement everything yourself, I would recommend to take a look at this tutorial (part of Cryptolens)
Besides what has already been stated....
Any use of .NET applications are inherently breakable because of the intermediate language issues. A simple disassembly of the .NET code will open your product to anyone. They can easily bypass your licensing code at that point.
You can't even use hardware values to create a key anymore. Virtual machines now allow someone to create an image of a 'licensed' machine and run it on any platform they choose.
If it's expensive software there are other solutions. If it's not, just make it difficult enough for the casual hacker. And accept the fact that there will be unlicensed copies out there eventually.
If your product is complicated, the inherent support issues will be create some protection for you.
The C# / .NET engine we use for licence key generation is now maintained as open source:
https://github.com/appsoftware/.NET-Licence-Key-Generator.
It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.
As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.
I've used Crypkey in the past. It's one of many available.
You can only protect software up to a point with any licensing scheme.
I don't know how elaborate you want to get
but i believe that .net can access the hard drive serial number.
you could have the program send you that and something eles ( like user name and mac address of the nic)
you compute a code based off that and email them back the key.
they will keep them from switching machines after they have the key.
I strongly believe, that only public key cryptography based licensing system is the right approach here, because you don't have to include essential information required for license generation into your sourcecode.
In the past, I've used Treek's Licensing Library many times, because it fullfills this requirements and offers really good price. It uses the same license protection for end users and itself and noone cracked that until now. You can also find good tips on the website to avoid piracy and cracking.
The only way to do everything you asked for is to require an internet access and verification with a server. The application needs to sign in to the server with the key, and then you need to store the session details, like the IP address. This will prevent the key from being used on several different machines. This is usually not very popular with the users of the application, and unless this is a very expensive and complicated application it's not worth it.
You could just have a license key for the application, and then check client side if the key is good, but it is easy to distribute this key to other users, and with a decompiler new keys can be generated.
I've implemented internet-based one-time activation on my company's software (C# .net) that requires a license key that refers to a license stored in the server's database. The software hits the server with the key and is given license information that is then encrypted locally using an RSA key generated from some variables (a combination of CPUID and other stuff that won't change often) on the client computer and then stores it in the registry.
It requires some server-side coding, but it has worked really well for us and I was able to use the same system when we expanded to browser-based software. It also gives your sales people great info about who, where and when the software is being used. Any licensing system that is only handled locally is fully vulnerable to exploitation, especially with reflection in .NET. But, like everyone else has said, no system is wholly secure.
In my opinion, if you aren't using web-based licensing, there's no real point to protecting the software at all. With the headache that DRM can cause, it's not fair to the users who have actually paid for it to suffer.
You can use a free third party solution to handle this for you such as Quantum-Key.Net It's free and handles payments via paypal through a web sales page it creates for you, key issuing via email and locks key use to a specific computer to prevent piracy.
Your should also take care to obfuscate/encrypt your code or it can easily be reverse engineered using software such as De4dot and .NetReflector. A good free code obfuscator is ConfuserEx wich is fast and simple to use and more effective than expensive alternatives.
You should run your finished software through De4Dot and .NetReflector to reverse-engineer it and see what a cracker would see if they did the same thing and to make sure you have not left any important code exposed or undisguised.
Your software will still be crackable but for the casual cracker it may well be enough to put them off and these simple steps will also prevent your code being extracted and re-used.
https://quantum-key.net
How to use ConfuserEx?
https://github.com/0xd4d/de4dot
https://www.red-gate.com/dynamic/products/dotnet-development/reflector/download
I know this is an old question, but I referenced this when I was re-writing my licensing process for one of my applications.
After reading a lot of opinions out there and relying on past experience with license codes I came up with this process.
public static class LicenseGenerator
{
private static string validChars = "ACEFHJKMNPRSTUVWXYZ234579";
private static Random rnd = new Random(Guid.NewGuid().GetHashCode());
/// <summary>
/// Generate a license code
/// </summary>
/// <param name="length">length of each phrase</param>
/// <param name="number">number of phrases separated by a '-'</param>
/// <returns></returns>
public static string GetNewCode(int length, int number)
{
string license = string.Empty;
for (int numberOfPhrases = 0; numberOfPhrases < number; numberOfPhrases++)
{
license += getPhrase(length);
if (numberOfPhrases < number)
license += "-";
}
return license.TrimEnd('-');
}
/// <summary>
/// generate a phrase
/// </summary>
/// <param name="length">length of phrase</param>
/// <returns></returns>
private static string getPhrase(int length)
{
string phrase = string.Empty;
for (int loop = 0; loop < length; loop++)
{
phrase += validChars[rnd.Next(validChars.Length)];
}
return phrase;
}
}
You really don't want to provide a code that has similar letters; it makes for a mess when the end user goes to enter it in. Letters like 6 and G, B and 8, L, I, and 1. Of course if you do want them, you can always add them back in... The above code will generate a license like xxxx-xxxx-xxxx-xxxx using the characters in "validChars". Calling GetNewCode(4, 4) will return a code like above.
I'm using Azure functions to register then validate the code. When my app registers the code, it generates an encrypted hash with things that are unique to the install, device and/or user. That is provided to the registration function and is stored with the key in the DB in Azure.
The validate regenerates the key and provides it with the license code, IP address (which in my case will not change and if it does then it will need to be updated anyway), and the regenerated hash then the Azure function returns if the application is licensed. I do store a "temporary" key on their server that allows the app to run for a period of time without talking back up.
Of course, my app must be on the net for it to work regardless.
So, the end result is a simple key for the end user to type in and an easy process to manage the license on the backend. I can also invalidate a license if need be.
I solved it by interfacing my program with a discord server, where it checks in a specific chat if the product key entered by the user exists and is still valid. In this way to receive a product key the user would be forced to hack discord and it is very difficult.

Categories