Category Archives: CodeProject

Using SSH Keys for License generation and validation in .NET Applications


license_generationpng

This blog post is going to present how can you implement license functionality in your .NET application. Providing license in your .NET application is very challenging because there is no standard procedure for the implementation. You are free to use whatever you want. But be notice, there is no license which is 100% safe and cannot be cracked or bypassed.

For this purpose I have selected the CocoaFob library for registration code generation and verification in Objective-C applications. Mainly the library is for Objective -C based applications, like iQS mobile applications and other OSX based applications.  This is very interesting library but you cannot use it in .NET applications, there is no implementation for .NET Framework.

The library uses DSA to generate registration keys, which is very hard for hackers to produce key generators. The library is also specific because it generates license key in human readable form, when the bytes are converted in to Base32 string to avoid ambiguous characters. It also groups codes in sets of five characters separated by dashes. Also DSA has encryption algorithm generates the license which is different every time because of a random element introduced during the process.

So the License key is produced using a 512-bit DSA key looks like on the following sample:

GAWQE-FCUGU-7Z5JE-WEVRA-PSGEQ-Y25KX-9ZJQQ-GJTQC-CUAJL-ATBR9-WV887-8KAJM-QK7DT-EZHXJ-CR99C-A

More information about CocoaFob can be found at GitHub page: https://github.com/glebd/cocoafob

The library is using BouncyCastle.Crypto Nuget package for DSA encryption and decryption.

The library CocoaFob for .NET contains two classes:

  1. LicenseData class which provide License properties which is used in license generation. It an be anything: Name, Product number, email, date of expiration etc.
  2. LicenseGenerator  class which is responsible for encrypting and validating the license.

For this blog post the License data class has the flowing implementation:

public class LicenseData
{

protected internal string productCode;
protected internal string name;
protected internal string email;

public virtual string toLicenseStringData()
{
 StringBuilder result = new StringBuilder();
 if (productCode != null)
 {
 result.Append(productCode);
 result.Append(',');
 }

 //name is mandatory property
 if (name == null)
 throw new System.Exception("name cannot be null");
 result.Append(name);

 if (email != null)
 {
 result.Append(',');
 result.Append(email);
 }
 return result.ToString();
}
......
}

As can be seen from the code snippet above the License data contains username, product key and email address. Also, only name property is mandatory, which means you can generate license key based on the user name only.

Generating the License Key

One we have License data we can process of License key generation. License is generated using DSA encryption which uses SSH private key.  You can generate public and private SSH keys  using any of the available tools, eg. OpenSSH, GitHub bash, …. More information about private and public key generation you can find at this link. Once we have public and private keys we can generate license and validate it. One important thing to remember is that you have to care about your private key. It should always be secure and no one should have access to it.

The public key is used for license validation, and it is usualy packed with the application as a part of the deployment stuff. So the process of generating the license is show on the flowing code snippet:

public string makeLicense(LicenseData licenseData)
{
     if (!CanMakeLicenses)
     {
       throw new System.InvalidOperationException("The LicenseGenerator cannot make licenses as it was not configured with a private key");
     }
     try
     {
        //
        var dsa = SignerUtilities.GetSigner("SHA1withDSA");
        dsa.Init(true, privateKey);
        //
        string stringData = licenseData.toLicenseStringData();
        byte[] licBytes = Encoding.UTF8.GetBytes(stringData);
        dsa.BlockUpdate(licBytes, 0, licBytes.Length);
        //
        byte[] signed = dsa.GenerateSignature();
        string license = ToLicenseKey(signed);
        return license;
    }
    catch (Exception e)
    {
        throw new LicenseGeneratorException(e);
    }
}

First the DSA encryption is created based on the publicKey we have provided as an argument. Then licBytes is generated from the License data, and converted in to UTF8 formatted bytes. Then we have update DSA provider with licBytes. Now the DSA provider can generate signature in bytes. The signature is converted in to LicenseKey by calling ToLicenseKey method. The method is shown on the following code snippet:

private string ToLicenseKey(byte[] signature)
{
    /* base 32 encode the signature */
    var result = Base32.ToString(signature);

    /* replace O with 8 and I with 9 */
    result = result.Replace("O", "8").Replace("I", "9");

    /* remove padding if any. */
    result = result.Replace("=", "");
           

    /* chunk with dashes */
    result = split(result, 5);
    return result;
}

The magic happen in this method during the conversion of signature from bytes to human readable string. Conversion is done using Base32 string helper method.

Verify the License Key

The License verification process is defined in varifyLicense method. You have to provide SSH publicKey as well as

public virtual bool verifyLicense(LicenseData licenseData, string license)
{
	if (!CanVerifyLicenses)
	{
		throw new System.InvalidOperationException("The LicenseGenerator cannot verify licenses as it was not configured with a public key");
	}
    try
     {
        //Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
        var dsa = SignerUtilities.GetSigner("SHA1withDSA");
        dsa.Init(false, publicKey);

        //
        string stringData = licenseData.toLicenseStringData();
        byte[] msgBytes = Encoding.UTF8.GetBytes(stringData);
        dsa.BlockUpdate(msgBytes, 0, msgBytes.Length);


        var dec = FromLicenseKey(license);
        var retVal = dsa.VerifySignature(dec);
        //
        return retVal; 
	}
    catch (Exception e)
    {
        throw new LicenseGeneratorException(e);
    }
}

As can be seen from the code above, the validation process is done by generating licenseData, converting the license Key in to signatere and the validation process return true is the license is valid, otherwize return false.

The whole project is published at git hub, an can be downloaded from http://github.com/bhrnjica/cocoafob

 

Testing the Library

The Library solution contains unit test project which you can see how to use this library in the real scenario in order to implement licensing in .NET app.

Happy programming!

Visual Studio vNext – The New Installer


Download Visual Studio 15 Preview 3

The new version of Visual Studio will come with dramatically new installer, which will allow that you install only stuff you need, without gigabytes of unnecessary never used components. Current version of Visual Studio which is Visual Studio 2015 Update 3 is coming with nearly 8GB installation file. This is to much for the installer, you need special condition when you want to download the installation file. I am doing it by night, when I am sleeping. In some condition the installation process takes an hour to install everything you have specified.

In the next version the installation process will be changed and if you want to see and feel how the future visual studio installer  will look like you can download the preview of the Visual Studio vnext code name  “Visual Studio 15” at this link.

If you try to install Visual Studio 15 preview 3, it will take less than 5 minutes, with very simple installer. In the next five pictures whole installation process is completed.

After you download the installer, run it and the following pictures will appear:

  1. First picture is asking to confirm the installation process:

vs15_sl01

2. The next picture shows the progress of loading installer

vs15_sl02

3. The next picture is the main picture which you can select what to install. The whole Visual Studio installer is devided in to the development groups:

  1. Core Stuff of the Visual Studio- this component is required for all developer group
  2. There are for now 4 installer groups: .NET, C++, Python, Game dev.
  3. The more will come later.
    vs15_sl03

4. After you select right developer group/groups installation process starts by pressing Install button.

vs15_sl04

5. After the installation process is completed, the following picture appear, which you only need to close by pressing the Close button at the right top edge of the window.

vs15_sl05

As we can see the next version of the Visual Studio will dramatically changed the installation process, offering new simple and effective installer.

Using external config files in .NET applications


The config file is place where common variables, database connection strings, web page settings and other common stuff are placed. The config file is also dynamic, so you can change the value of the variable in the config file  without compiling and deploying the .NET app. In multi tenancy environment config file can be complicate for deployment, because  for each tenant different value must be set for most of the defined variables. In such a situation you have to be careful to set right value for the right tenant.

One way of handling this is to hold separate config file for each tenant. But the problem can be variables which are the same for all tenants, and also the case where some variables can be omitted for certain tenant.

One of the solution for this can be defining external config files for only connection strings or appSettings variables, or any other custom config section. In this blog post, it will be presenting how to define connection strings as well as appSettings section in separate config file.

Lets say you have appSettings and connectionStrings config sections, similar like code below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

	<connectionStrings>
		<add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
		<add name="SQLConnectionString02" connectionString="Data Source=sourcename02;Initial Catalog=cat02;Persist Security Info=True;Integrated Security=true;"/>
	</connectionStrings>

	<appSettings>
		<clear />
		<!-- Here are list of appsettings -->
		<add key="Var1" value="Var1 value from config01" />
		<add key="Var2" value="Varn value from config01"/>
		<add key="Var3" value="Var3 value from main config file"/>
	</appSettings>

</configuration>

There are three appSetting keys Var1 , Var2 and Var3  and two connectionstrings in the app.config.

The config file above can be split in such a way that variables Var1 and Var2 be defined in separated file, but the Var3 can be remain in the main cofing file. Separate config file may be unique for each tenant.

Now the main config file looks like the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

	<connectionStrings configSource="config\connString01.config"/>

	<appSettings file="config\config01.config">
		
		<add key="Var3" value="Var3 value from main config file"/>
	</appSettings>

</configuration>

In the Visual Studio Solution there is config folder in which we created two config files for appSettings section and two config files for Connectionstrings section, in case we have two separate environments for deployments.

exconfigfile01
The flowing code snippet shows the appSettings section implemented in the external file:

<appSettings file="appSettings.config">

	<!-- Here are list of appsettings -->
	<add key="Var1" value="Var1 value from config02" />
	<!-- ... -->
	<add key="Varn" value="Varn value from config02"/>
</appSettings>

The external config file for connection strings looks similar like the flowing:

exconfigfile02

The simple console application shows how to use this config variables in the code:

static void Main(string[] args)
{
    var var1Value= ConfigurationManager.AppSettings["Var1"];
    var var2Value = ConfigurationManager.AppSettings["Var2"];
    var var3Value = ConfigurationManager.AppSettings["Var3"];
    var conn1 = ConfigurationManager.ConnectionStrings["SQLConnectionString01"];
    var conn2 = ConfigurationManager.ConnectionStrings["SQLConnectionString02"];

    Console.WriteLine("Values from config01.config and connString01.config files");

    Console.WriteLine("Var1={0}",var1Value);
    Console.WriteLine("Var2={0}", var2Value);
    Console.WriteLine("Var3={0}", var3Value);
    Console.WriteLine("ConnStr01={0}", conn1);
    Console.WriteLine("ConnStr01={0}", conn2);

    Console.Read();
}

The complete source code can be downloaded from this link.

New Features in C# 6.0 – Primary Constructors


Update: This feature is removed from the C# 6.0 specification, probably for the next version of C#.
Primary constructors reduced declaration of various constructors with different arguments. Primary constructors is declare on the type declaration and this is why it so special. For example:


public class Person (string defaultName)
{
 private string m_Name=defaultName;
 public string Name {get;set;}
 public Person()
 {
   Name=defaultName;
 }

}

We can define Primary Constructor in combination on Auto-Property Initializer on the following way:

public class Person (string defaultName)
{
 private string m_Name=defaultName;
 public string Name {get;set;}=defaultName

}