Click here to Skip to main content
15,878,871 members
Articles / Programming Languages / C++

Implementation of the Licensing System for a Software Product

,
Rate me:
Please Sign up or sign in to vote.
4.80/5 (47 votes)
5 Aug 2010CPOL6 min read 160.3K   14.1K   254   36
This article is devoted to the development of the key licensing system for the applications.

Table of Contents

Introduction

This article is devoted to the development of the key licensing system for the applications. In the theoretical part of the article, we will examine the cryptography methods, which can be used while implementing the licensing system. Also, we will discuss all pros and cons of these methods and select the possible ones for using in the application. In the practical part of the article, we will provide the implementation of the simplest licensing system, which guaranties the protection from cracking even if a hacker knows the source code of an algorithm.

Types of Algorithms

The cryptographic algorithm, also called cipher, is a mathematical function used for encryption and decryption. Usually, these are two interconnected functions: one is used for encryption, another is for decryption.

If the reliability of the algorithm is based on keeping the algorithm itself in secret, then this algorithm is limited. Limited algorithms do not correspond to the nowadays standards and represent only the historical value.

The modern cryptography solves these problems with the help of the key. The key can be of any value selected from a wide range of values. The set of possible keys is called the key space.

There are two main types of algorithms based on the key usage: symmetric-key algorithm and algorithm with the public key.

Symmetric-key algorithms, sometimes called the conditional algorithms, are the algorithms where the encryption key can be calculated by the decryption key and vice versa. The encryption and decryption keys are the same in most symmetric-key algorithms. These algorithms, also called one-key or secret-key algorithms, require that the sender and the recipient reconcile the used key before the beginning of the secure message exchange. The safety of the symmetric-key algorithms is defined by the key. The key disclosure means that anyone can encrypt and decrypt messages. The key must be kept in secret as long as the transmitted messages should be secret.

Algorithms with the public key, also called asymmetric-key algorithms, are developed in a way that the key used for the encryption differs from that for decryption. Moreover, the decryption key can't be calculated by the encryption key (at least, during the reasonable period of time). These algorithms are called “algorithms with the public key” because the encryption key can be open: anyone can use the encryption key for the encryption of the message but only one concrete person can decrypt the message with the corresponding decryption key. In these systems, the encryption key is often called the public key and the decryption key is called the private key. The private key is sometimes called the secret key.

It is obvious that the only type of the algorithm which suits us is the algorithm with the public key because we have to store the key in the program for the authentication of the entered serial key. When choosing these algorithms, we have the guarantee that the intruder, having the public key and the source code of the algorithm, won't be able to make the key generator and create serial keys for another program copies.

There are many computer algorithms. The following three algorithms are most frequently used:

  • DES (Data Encryption Standard) is the most popular computer encryption algorithm. It is the American and international standard. It is the symmetric-key algorithm where one and the same key is used for encryption and decryption.
  • RSA (which stands for Rivest, Shamir and Adleman who first publicly described it) is the most popular algorithm with the public key. It is used both for the encryption and for digital signature.
  • DSA (Digital Signature Algorithm, is used as the part of the Digital Signature Standard) is another algorithm with the public key. It is used only for the digital signature and can’t be used for the encryption.

DES does not suit us because it is the symmetric-key algorithm.

Two algorithms are left: RSA and DSA. It is easy to choose between them if we look at the structure of the work of these algorithms.

RSA uses the public key for the creation of the cipher text from the source text. We don't need it as it is supposed that we create and send keys and they will be decrypted and compared with the source value on the client side. As it was mentioned above, we can use only the public key on the client side in order not to compromise the licensing system.

Now some words about the work of DSA. Using the source text, DSA calculates the hash code and then “decrypts” it using the private key and receives the required serial key. It “encrypts” the received value on the client side and receives the hash code. Then it calculates the hash code from the source text in the usual way and compares two values. If these values coincide, then the serial key is valid.

svg2raster.png

The Crypto++® Library contains the implementation of many algorithms. I used this library in the example. For more information, see http://www.cryptopp.com/.

C++
................................
bool RsaVerifyVector(const std::string & publicKeyStrHex, 
	const std::string& source, const std::vector<char>& sign)
    {
        CryptoPP::HexDecoder decoder;
        decoder.Put( (byte*)publicKeyStrHex.c_str(), publicKeyStrHex.size() );
        decoder.MessageEnd();

        CryptoPP::RSA::PublicKey publicKey;
        publicKey.Load( decoder );

        // Verifier object
        CryptoPP::RSASS<CryptoPP::PSS, CryptoPP::SHA1>::Verifier verifier( publicKey );

        std::vector<char> rawSignature;
        std::string signStr(utils::GetBeginOf(sign), sign.size());
        utils::FromHexString(utils::string2wstring(signStr), &rawSignature);
        // Verify
        const char * pData = utils::GetBeginOf(source);
        return verifier.VerifyMessage( (const byte*) pData,
            source.size(), (const byte*) utils::GetBeginOf(rawSignature), 
		rawSignature.size() );
    }
………………………………………………
void RsaSignVector(const std::string & privateKeyStrHex, 
	const std::vector<char> & vec, std::string & sign)
    {
        // Pseudo Random Number Generator
        CryptoPP::AutoSeededRandomPool rng;
        // Generate Parameters
        CryptoPP::InvertibleRSAFunction params;
        params.GenerateRandomWithKeySize( rng, 1536 );

        CryptoPP::HexDecoder decoder;
        decoder.Put( (byte*)privateKeyStrHex.c_str(), privateKeyStrHex.size() );
        decoder.MessageEnd();

        CryptoPP::RSA::PrivateKey privateKey; // Private
        privateKey.Load( decoder );


        CryptoPP::RSASS<CryptoPP::PSS, CryptoPP::SHA1>::Signer signer( privateKey );

        size_t length = signer.MaxSignatureLength();
        CryptoPP::SecByteBlock signature( length );

        // Sign message
        signer.SignMessage( rng, (const byte*) utils::GetBeginOf(vec),
            vec.size(), signature );

        sign  = utils::wstring2string
	(utils::ToHexString<byte>(signature, signature.size()));
    }
………………………………………
void RsaGenerateStringKeys(std::string & publicKeyStr, std::string & privateKeyStr)
    {
        // Pseudo Random Number Generator
        CryptoPP::AutoSeededRandomPool rng;

        // Generate Parameters
        CryptoPP::InvertibleRSAFunction params;
        params.GenerateRandomWithKeySize( rng, 1536 );

        CryptoPP::RSA::PrivateKey privateKey( params );
        CryptoPP::RSA::PublicKey publicKey( params );

        CryptoPP::HexEncoder encoder;

        // save public Key
        encoder.Attach( new CryptoPP::StringSink( publicKeyStr ) );
        publicKey.Save( encoder );

        // save private Key
        encoder.Attach( new CryptoPP::StringSink( privateKeyStr ) );
        privateKey.Save( encoder );
    }
………………………………

Hardware Serial Key

We need to have the unique identifier of the computer in order to make sure that our serial key is used on the computer where we granted a license. There are many methods of its obtaining. But we chose HardDisk Serial Key for this case. It has a rather readable form and small size, but the probability of collisions is very low.

C++
BOOL CSmartReader::ReadSMARTInfo(BYTE ucDriveIndex)
{
    HANDLE hDevice=NULL;
    WCHAR wTempDriveName[MAX_PATH]={0};
    BOOL bRet=FALSE;
    DWORD dwRet=0;

    wsprintf(wTempDriveName,L"\\\\.\\PHYSICALDRIVE%d",ucDriveIndex);
    hDevice=CreateFile(wTempDriveName,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|
	FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,NULL);
    if(hDevice!=INVALID_HANDLE_VALUE)
    {
        bRet=DeviceIoControl(hDevice,SMART_GET_VERSION,NULL,0,
	&m_stDrivesInfo[ucDriveIndex].m_stGVIP,sizeof(GETVERSIONINPARAMS),&dwRet,NULL);
        if(bRet)
        {			
            if((m_stDrivesInfo[ucDriveIndex].m_stGVIP.fCapabilities & 
					CAP_SMART_CMD)==CAP_SMART_CMD)
            {
                if(IsSmartEnabled(hDevice,ucDriveIndex))
                {
                    bRet=CollectDriveInfo(hDevice,ucDriveIndex);
                    bRet=ReadSMARTAttributes(hDevice,ucDriveIndex);
                }
            }
        }
        CloseHandle(hDevice);
    }
    return bRet;
}
……………………
BOOL CSmartReader::CollectDriveInfo(HANDLE hDevice,UCHAR ucDriveIndex)
{
    BOOL bRet = FALSE;
    SENDCMDINPARAMS stCIP = {0};
    DWORD dwRet = 0;
    char szOutput[OUT_BUFFER_SIZE] = {0};

    stCIP.cBufferSize=IDENTIFY_BUFFER_SIZE;
    stCIP.bDriveNumber =ucDriveIndex;
    stCIP.irDriveRegs.bFeaturesReg=0;
    stCIP.irDriveRegs.bSectorCountReg = 1;
    stCIP.irDriveRegs.bSectorNumberReg = 1;
    stCIP.irDriveRegs.bCylLowReg = 0;
    stCIP.irDriveRegs.bCylHighReg = 0;
    stCIP.irDriveRegs.bDriveHeadReg = DRIVE_HEAD_REG;
    stCIP.irDriveRegs.bCommandReg = ID_CMD;

    bRet=DeviceIoControl(hDevice,SMART_RCV_DRIVE_DATA,&stCIP,
	sizeof(stCIP),szOutput,OUT_BUFFER_SIZE,&dwRet,NULL);
    if(bRet)
    {
        CopyMemory(&m_stDrivesInfo[ucDriveIndex].m_stInfo, 
	szOutput+16, sizeof(ST_IDSECTOR));
        ConvertString(m_stDrivesInfo[ucDriveIndex].m_stInfo.sSerialNumber, 20);
    }
    else
    {
        dwRet=GetLastError();
    }
    return bRet;
}

As can be seen, we receive the information about hard drives, including the sSerialKey, which was mentioned above.

So, we have the algorithms of signing, verification, and acquiring of the disk serial number.

The Scheme of the Licensing System

We can see the common scheme of the work of the licensing system.

schema.png

The LicenseManager source code is the following:

C++
……………………………………………………
std::string publicKey;
    std::string privateKey;

    std::vector<char> vecPrivate;   

    utils::SaveResToVector(L"PRIVATE_KEY", IDR_FILE_PRIVATE_KEY, &vecPrivate );

    //this is an example of how to generate public and private keys
    //you need to save them in .rc files or somewhere else after they are first generated
    if (vecPrivate.empty())
    {
        utils::RsaGenerateStringKeys(publicKey, privateKey);
        std::vector<char> vecPublic(publicKey.begin(), publicKey.end());
        vecPrivate.assign(privateKey.begin(), privateKey.end());
        utils::SaveVectorToFile(L"keys\\private.bin", vecPrivate);
        utils::SaveVectorToFile(L"keys\\public.bin", vecPublic);
    }
    else
    {
        privateKey.assign(vecPrivate.begin(), vecPrivate.end());
    }
    
    std::string sign;
    
    std::vector<char> smallFile;
    std::string serialKey;

    //Input the hardware serial key, that your client application will give you
    std::cout << "Input your serial key here : ";
    std::cin >> serialKey;
    
    //make it vector and sign using utils
    std::vector<char> hardwareSerialKey(serialKey.begin(), serialKey.end());
    utils::RsaSignVector(privateKey, hardwareSerialKey, sign);

    //save signed value to the file and send the file to user
    std::vector<char> vec(sign.begin(), sign.end());
    utils::SaveVectorToFile(L"License.dat", vec);

    std::cout << "Your license.dat file was saved in program's directory" << std::endl;
    std::cout << "Press any key...";
    std::cin.get();

    return 0;
……………………………

The client side looks like the following:

C++
………………………………………
std::string publicKey;
    std::vector<char> vecPublic;
    utils::SaveResToVector(L"PUBLIC_KEY", IDR_FILE_PUBLIC_KEY, &vecPublic);
    if (vecPublic.empty())
    {
        std::cout << "Cant find public key\nPress Any key..." << std::endl;
        std::cin.get();
        return 0;
    }
    publicKey.assign(vecPublic.begin(), vecPublic.end());
    CSmartReader reader;
    
    ST_IDSECTOR *pSectorInfo = NULL;
    
    reader.ReadSMARTValuesForAllDrives();
    
    pSectorInfo=&reader.m_stDrivesInfo[0].m_stInfo;
    
    std::string str(pSectorInfo->sSerialNumber);

    std::stringstream trimmer;
    trimmer << str;
    trimmer >> str;

    std::cout << "Your hardware Serial Key is : " << str << std::endl;
    
    try
    {
        std::vector<char> vec;
        const std::wstring fileName = L"License.dat";
        utils::LoadFileToVector(fileName, vec);

        if (utils::RsaVerifyVector(publicKey, str, vec))
        {
            std::cout << "License is valid. Continue working" << std::endl;
        }
        else
        {
            std::cout << "License is invalid. Program is being closed" << std::endl;
        }
    }
    catch(const std::logic_error& ex)
    {
        std::cout << "You do not have license.dat file installed. 
			Please put it in program dir." << std::endl;
    }

    std::cout << "Press any key...";
    std::cin.get();
……………………………………………………

The Folders Structure

  • .\ClientTest – The client side
  • .\DigitalSignature – The License Manager side
  • .\Utils – Utilities and wrappers for the Crypto++® Library
  • .\ cryptopp560 – Crypto++® Library

Bibliography List

  1. C.M. Adams and H. Mailer, "Security Related Comments Regarding McEliece's Public-Key Cryptosystem" Advances in Cryptology CRYPTO '87 Proceedings, Springer-Verlag, 1988, pp. 224-230.
  2. Cylink Corporation, Cylink Corporation vs. RSA Data Security, Inc., Civil Action No. C94-02332-CW, United States District Court for the Northern District of California, 30 Jun 1994.
  3. G.I. Davida, "Chosen Signature Cryptanalysis of the RSA iMITJ Public Key Cryptosystem," Technical Report TR-CS-82-2, Department of EECS, University of Wis- consin, 1982.
  4. I.M. DeLaurentis, "A Further Weakness in the Common Modulus Protocol for the RSA Cryptosystem," Cryptologia, v. 8, n. 3, Jul 1984, pp. 253-259.
  5. Schneier, Bruce. Applied Cryptography, Second Edition, John Wiley & Sons, 1996. ISBN 0-471-11709-9.

History

  • 5th August, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Apriorit Inc.
United States United States
ApriorIT is a software research and development company specializing in cybersecurity and data management technology engineering. We work for a broad range of clients from Fortune 500 technology leaders to small innovative startups building unique solutions.

As Apriorit offers integrated research&development services for the software projects in such areas as endpoint security, network security, data security, embedded Systems, and virtualization, we have strong kernel and driver development skills, huge system programming expertise, and are reals fans of research projects.

Our specialty is reverse engineering, we apply it for security testing and security-related projects.

A separate department of Apriorit works on large-scale business SaaS solutions, handling tasks from business analysis, data architecture design, and web development to performance optimization and DevOps.

Official site: https://www.apriorit.com
Clutch profile: https://clutch.co/profile/apriorit
This is a Organisation

33 members

Written By
Technical Lead Apriorit Inc.
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalvery good Pin
Southmountain30-Aug-20 8:05
Southmountain30-Aug-20 8:05 
QuestionGreat job, but! Pin
Razvan Cristian27-Feb-17 10:53
Razvan Cristian27-Feb-17 10:53 
AnswerRe: Great job, but! Pin
Rick York27-Feb-17 11:35
mveRick York27-Feb-17 11:35 
GeneralRe: Great job, but! Pin
Razvan Cristian27-Feb-17 12:16
Razvan Cristian27-Feb-17 12:16 
QuestionFrom where I can get License.dat file Pin
Member 238154124-Mar-16 12:08
Member 238154124-Mar-16 12:08 
QuestionVisual Studio 2005 Pin
Member 1126979930-Nov-14 12:41
Member 1126979930-Nov-14 12:41 
QuestionWindows 7 Compatibality Issues Pin
Rajan Paudel17-Sep-12 21:23
Rajan Paudel17-Sep-12 21:23 
GeneralMy vote of 5 Pin
gndnet11-Sep-12 0:23
gndnet11-Sep-12 0:23 
GeneralMy vote of 5 Pin
gndnet18-Jul-12 0:02
gndnet18-Jul-12 0:02 
thanks
GeneralMy vote of 5 Pin
gndnet17-Jul-12 15:35
gndnet17-Jul-12 15:35 
QuestionPossible hack for this implementation Pin
Nizam1115-Feb-12 0:21
Nizam1115-Feb-12 0:21 
GeneralQuestion about self-decryption Pin
yasihunter13-Apr-11 3:28
yasihunter13-Apr-11 3:28 
GeneralRe: Question about self-decryption Pin
Sergii Bratus13-Apr-11 23:00
Sergii Bratus13-Apr-11 23:00 
GeneralMy vote of 5 Pin
gndnet8-Jan-11 20:45
gndnet8-Jan-11 20:45 
GeneralMultiple application [modified] Pin
aldo hexosa5-Oct-10 23:41
professionalaldo hexosa5-Oct-10 23:41 
GeneralMy vote of 5 Pin
R&D Ninja4-Oct-10 5:27
R&D Ninja4-Oct-10 5:27 
Questionhow to avoid if(A==B)? Pin
NewttleLi1-Sep-10 20:50
NewttleLi1-Sep-10 20:50 
AnswerRe: how to avoid if(A==B)? Pin
Chris Losinger17-Jan-12 3:59
professionalChris Losinger17-Jan-12 3:59 
Questionwhy is 1536? Pin
ftai24-Aug-10 20:48
ftai24-Aug-10 20:48 
GeneralMy vote of 5 Pin
Member 432084415-Aug-10 11:17
Member 432084415-Aug-10 11:17 
GeneralTimed License Pin
JeffBilkey11-Aug-10 14:33
JeffBilkey11-Aug-10 14:33 
GeneralSuggestions.... Pin
VaKa11-Aug-10 9:06
VaKa11-Aug-10 9:06 
QuestionNeed more explanation Pin
PatLeCat9-Aug-10 23:18
PatLeCat9-Aug-10 23:18 
GeneralMy vote of 3 Pin
PatLeCat9-Aug-10 23:14
PatLeCat9-Aug-10 23:14 
GeneralGood start. Pin
John M. Drescher8-Aug-10 4:29
John M. Drescher8-Aug-10 4:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.