From bc33836f06e315005db152854ceaa199ed752820 Mon Sep 17 00:00:00 2001
From: open-license-manager <rillf@maildrop.cc>
Date: 周一, 13 10月 2014 06:24:56 +0800
Subject: [PATCH] linux build

---
 src/scratch/linux/os-linux.cpp                 |   64 ++
 /dev/null                                      |  215 ---------
 src/library/os/win/CMakeLists.txt              |    1 
 src/library/LicenseReader.cpp                  |    2 
 src/library/os/win/os-win.c                    |  156 +++---
 src/scratch/linux/bootstrap_linux.cpp          |    0 
 src/tools/base_lib/win/CryptoHelperWindows.cpp |  724 ++++++++++++++-----------------
 src/library/os/linux/CMakeLists.txt            |    1 
 src/library/os/linux/os-linux.c                |   92 +++
 src/scratch/linux/LicenseSigner_linux.cpp      |    0 
 src/scratch/win/Copy of Main.cpp               |  125 +++++
 11 files changed, 665 insertions(+), 715 deletions(-)

diff --git a/src/library/LicenseReader.cpp b/src/library/LicenseReader.cpp
index 7b1ae65..e9abce6 100644
--- a/src/library/LicenseReader.cpp
+++ b/src/library/LicenseReader.cpp
@@ -25,8 +25,6 @@
 #include "public-key.h"
 #include <build_properties.h>
 
-#include "os/os-cpp.h"
-
 namespace license {
 
 const char *FullLicenseInfo::UNUSED_TIME = "0000-00-00";
diff --git a/src/library/os/linux/CMakeLists.txt b/src/library/os/linux/CMakeLists.txt
index 014f98c..fb41404 100644
--- a/src/library/os/linux/CMakeLists.txt
+++ b/src/library/os/linux/CMakeLists.txt
@@ -1,7 +1,6 @@
 ADD_LIBRARY(os STATIC
 	os-linux.c
 	network_id.c
-    os-linux.cpp
 )
 
 target_link_libraries(
diff --git a/src/library/os/linux/os-linux.c b/src/library/os/linux/os-linux.c
index 1b46dfc..7469d83 100644
--- a/src/library/os/linux/os-linux.c
+++ b/src/library/os/linux/os-linux.c
@@ -1,4 +1,3 @@
-
 #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
@@ -15,6 +14,7 @@
 #include <sys/stat.h>
 #include "../os.h"
 #include "public-key.h"
+#include "../../base/logger.h"
 
 #include <openssl/evp.h>
 #include <openssl/bio.h>
@@ -117,10 +117,8 @@
 					}
 				}
 				if (drive_found == -1) {
-#ifdef _DEBUG
-					printf("mntent: %s %s %d\n", ent->mnt_fsname, ent->mnt_dir,
-							mount_stat.st_ino);
-#endif
+					LOG_DEBUG("mntent: %s %s %d\n", ent->mnt_fsname, ent->mnt_dir,
+							(unsigned long int)mount_stat.st_ino);
 					strcpy(tmpDrives[currentDrive].device, ent->mnt_fsname);
 					statDrives[currentDrive] = mount_stat.st_ino;
 					drive_found = currentDrive;
@@ -128,9 +126,7 @@
 				}
 				if (strcmp(ent->mnt_dir, "/") == 0) {
 					strcpy(tmpDrives[drive_found].label, "root");
-#ifdef _DEBUG
-					printf("drive %s set to preferred\n", ent->mnt_fsname);
-#endif
+					LOG_DEBUG("drive %s set to preferred\n", ent->mnt_fsname);
 					tmpDrives[drive_found].preferred = true;
 				}
 			}
@@ -145,9 +141,7 @@
 	} else if (*disk_info_size >= currentDrive) {
 		disk_by_uuid_dir = opendir("/dev/disk/by-uuid");
 		if (disk_by_uuid_dir == NULL) {
-#ifdef _DEBUG
-			printf("Open /dev/disk/by-uuid fail");
-#endif
+			LOG_WARN("Open /dev/disk/by-uuid fail");
 			free(statDrives);
 			return FUNC_RET_ERROR;
 		}
@@ -164,7 +158,7 @@
 #ifdef _DEBUG
 						VALGRIND_CHECK_VALUE_IS_DEFINED(tmpDrives[i].device);
 
-						printf("uuid %d %s %02x%02x%02x%02x\n", i,
+						LOG_DEBUG("uuid %d %s %02x%02x%02x%02x\n", i,
 								tmpDrives[i].device,
 								tmpDrives[i].disk_sn[0],
 								tmpDrives[i].disk_sn[1],
@@ -312,3 +306,77 @@
 	}
 	return result;
 }
+
+static void free_resources(EVP_PKEY* pkey, EVP_MD_CTX* mdctx) {
+	if (pkey) {
+		EVP_PKEY_free(pkey);
+	}
+	if (mdctx) {
+		EVP_MD_CTX_destroy(mdctx);
+	}
+}
+
+FUNCTION_RETURN verifySignature(const char* stringToVerify,
+		const char* signatureB64) {
+	EVP_MD_CTX *mdctx = NULL;
+	const char *pubKey = PUBLIC_KEY;
+	int func_ret = 0;
+
+	BIO* bio = BIO_new_mem_buf((void*) (pubKey), strlen(pubKey));
+	RSA *rsa = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL);
+	BIO_free(bio);
+	if (rsa == NULL) {
+		LOG_ERROR("Error reading public key");
+		return FUNC_RET_ERROR;
+	}
+	EVP_PKEY *pkey = EVP_PKEY_new();
+	EVP_PKEY_assign_RSA(pkey, rsa);
+
+	/*BIO* bo = BIO_new(BIO_s_mem());
+	 BIO_write(bo, pubKey, strlen(pubKey));
+	 RSA *key = 0;
+	 PEM_read_bio_RSAPublicKey(bo, &key, 0, 0);
+	 BIO_free(bo);*/
+
+//RSA* rsa = EVP_PKEY_get1_RSA( key );
+//RSA * pubKey = d2i_RSA_PUBKEY(NULL, <der encoded byte stream pointer>, <num bytes>);
+	unsigned char buffer[512];
+	BIO* b64 = BIO_new(BIO_f_base64());
+	BIO* encoded_signature = BIO_new_mem_buf((void *) signatureB64,
+			strlen(signatureB64));
+	BIO* biosig = BIO_push(b64, encoded_signature);
+	BIO_set_flags(biosig, BIO_FLAGS_BASE64_NO_NL); //Do not use newlines to flush buffer
+	unsigned int len = BIO_read(biosig, (void *) buffer, strlen(signatureB64));
+//Can test here if len == decodeLen - if not, then return an error
+	buffer[len] = 0;
+
+	BIO_free_all(biosig);
+
+	/* Create the Message Digest Context */
+	if (!(mdctx = EVP_MD_CTX_create())) {
+		free_resources(pkey, mdctx);
+		LOG_ERROR("Error creating context");
+		return FUNC_RET_ERROR;
+	}
+	if (1 != EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey)) {
+		LOG_ERROR("Error initializing digest");
+		free_resources(pkey, mdctx);
+		return FUNC_RET_ERROR;
+	}
+	int en = strlen(stringToVerify);
+	func_ret = EVP_DigestVerifyUpdate(mdctx, stringToVerify, en);
+	if (1 != func_ret) {
+		LOG_ERROR("Error verifying digest %d", func_ret);
+		free_resources(pkey, mdctx);
+		return FUNC_RET_ERROR;
+	}
+	FUNCTION_RETURN result;
+	func_ret = EVP_DigestVerifyFinal(mdctx, buffer, len);
+	if (1 != func_ret) {
+		LOG_ERROR("Error verifying digest %d", func_ret);
+	}
+	result = (1 == func_ret ? FUNC_RET_OK : FUNC_RET_ERROR);
+
+	free_resources(pkey, mdctx);
+	return result;
+}
diff --git a/src/library/os/linux/os-linux.cpp b/src/library/os/linux/os-linux.cpp
deleted file mode 100644
index fffd816..0000000
--- a/src/library/os/linux/os-linux.cpp
+++ /dev/null
@@ -1,126 +0,0 @@
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE     /* To get defns of NI_MAXSERV and NI_MAXHOST */
-#endif
-#include <arpa/inet.h>
-#include <sys/socket.h>
-#include <netdb.h>
-#include <ifaddrs.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <linux/if_link.h>
-#include <sys/socket.h>
-#include <netpacket/packet.h>
-
-#include <paths.h>
-
-#include <stdlib.h>
-#include <cstring>
-#include <string>
-#include <system_error>
-#include <unistd.h>
-#include <sstream>
-#include <sys/ioctl.h>
-#include <sys/stat.h>
-#include "../os-cpp.h"
-#include "public-key.h"
-
-#include <openssl/evp.h>
-#include <openssl/bio.h>
-#include <openssl/pem.h>
-#include <openssl/err.h>
-
-namespace license {
-
-using namespace std;
-
-
-bool OsFunctions::verifySignature(const char* stringToVerify,
-		const char* signatureB64) {
-	EVP_MD_CTX *mdctx = NULL;
-
-	const char *pubKey = PUBLIC_KEY;
-
-	BIO* bio = BIO_new_mem_buf((void*) (pubKey), strlen(pubKey));
-	RSA *rsa = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL);
-	BIO_free(bio);
-	if (rsa == NULL) {
-		throw new logic_error("Error reading public key");
-	}
-	EVP_PKEY *pkey = EVP_PKEY_new();
-
-	EVP_PKEY_assign_RSA(pkey, rsa);
-
-	/*BIO* bo = BIO_new(BIO_s_mem());
-	 BIO_write(bo, pubKey, strlen(pubKey));
-	 RSA *key = 0;
-	 PEM_read_bio_RSAPublicKey(bo, &key, 0, 0);
-	 BIO_free(bo);*/
-
-//RSA* rsa = EVP_PKEY_get1_RSA( key );
-//RSA * pubKey = d2i_RSA_PUBKEY(NULL, <der encoded byte stream pointer>, <num bytes>);
-	unsigned char buffer[512];
-	BIO* b64 = BIO_new(BIO_f_base64());
-	BIO* encoded_signature = BIO_new_mem_buf((void *) signatureB64,
-			strlen(signatureB64));
-	BIO* biosig = BIO_push(b64, encoded_signature);
-	BIO_set_flags(biosig, BIO_FLAGS_BASE64_NO_NL); //Do not use newlines to flush buffer
-	unsigned int len = BIO_read(biosig, (void *) buffer, strlen(signatureB64));
-//Can test here if len == decodeLen - if not, then return an error
-	buffer[len] = 0;
-
-	BIO_free_all(biosig);
-
-	/* Create the Message Digest Context */
-	if (!(mdctx = EVP_MD_CTX_create())) {
-		throw new logic_error("Error creating context");
-	}
-	if (1 != EVP_DigestVerifyInit(mdctx, NULL, EVP_sha256(), NULL, pkey)) {
-		throw new logic_error("Error initializing digest");
-	}
-	int en = strlen(stringToVerify);
-	if (1 != EVP_DigestVerifyUpdate(mdctx, stringToVerify, en)) {
-		throw new logic_error("Error verifying digest");
-	}
-	bool result;
-	int res = EVP_DigestVerifyFinal(mdctx, buffer, len);
-	if (1 == res) {
-		result = true;
-	} else {
-		result = false;
-	}
-	if (pkey) {
-		EVP_PKEY_free(pkey);
-	}
-	if (mdctx) {
-		EVP_MD_CTX_destroy(mdctx);
-	}
-	return result;
-}
-
-
-
-VIRTUALIZATION getVirtualization() {
-//http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html
-//
-//bool rc = true;
-	/*__asm__ (
-	 "push   %edx\n"
-	 "push   %ecx\n"
-	 "push   %ebx\n"
-	 "mov    %eax, 'VMXh'\n"
-	 "mov    %ebx, 0\n" // any value but not the MAGIC VALUE
-	 "mov    %ecx, 10\n"// get VMWare version
-	 "mov    %edx, 'VX'\n"// port number
-	 "in     %eax, dx\n"// read port on return EAX returns the VERSION
-	 "cmp    %ebx, 'VMXh'\n"// is it a reply from VMWare?
-	 "setz   [rc] \n"// set return value
-	 "pop    %ebx \n"
-	 "pop    %ecx \n"
-	 "pop    %edx \n"
-	 );*/
-
-	return NONE;
-}
-
-}
diff --git a/src/library/os/os-cpp.h b/src/library/os/os-cpp.h
deleted file mode 100644
index 5e0fe24..0000000
--- a/src/library/os/os-cpp.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * os-dependent.hpp
- *
- *  Created on: Mar 29, 2014
- *      
- */
-
-#ifndef OS_DEPENDENT_CPP_
-#define OS_DEPENDENT_CPP_
-
-/* deprecated: all os dependent functions have been implemented in C*/
-#include "os.h"
-
-namespace license {
-using namespace std;
-
-
-
-class OsFunctions {
-public:
-
-	//static string getModuleName();
-	//use system dependent methods to verify signature
-	static bool verifySignature(const char * stringToVerify,
-			const char* signature);
-
-};
-
-}
-
-#endif /* OS_DEPENDENT_HPP_ */
diff --git a/src/library/os/win/CMakeLists.txt b/src/library/os/win/CMakeLists.txt
index b3d2d38..044586d 100644
--- a/src/library/os/win/CMakeLists.txt
+++ b/src/library/os/win/CMakeLists.txt
@@ -1,6 +1,5 @@
 ADD_LIBRARY(os STATIC
 	os-win.c
-    os-win.cpp
 )
 
 target_link_libraries(
diff --git a/src/library/os/win/os-win.c b/src/library/os/win/os-win.c
index 169821b..10072f8 100644
--- a/src/library/os/win/os-win.c
+++ b/src/library/os/win/os-win.c
@@ -10,7 +10,7 @@
 #pragma comment(lib, "IPHLPAPI.lib")
 unsigned char* unbase64(const char* ascii, int len, int *flen);
 
-FUNCTION_RETURN getOsSpecificIdentifier(unsigned char identifier[6]){
+FUNCTION_RETURN getOsSpecificIdentifier(unsigned char identifier[6]) {
 	return FUNC_RET_NOT_AVAIL;
 }
 
@@ -18,9 +18,8 @@
 	FUNCTION_RETURN result = FUNC_RET_ERROR;
 	char buffer[MAX_COMPUTERNAME_LENGTH + 1];
 	int bufsize = MAX_COMPUTERNAME_LENGTH + 1;
-	BOOL cmpName = GetComputerName(
-		buffer, &bufsize);
-	if (cmpName){
+	BOOL cmpName = GetComputerName(buffer, &bufsize);
+	if (cmpName) {
 		strncpy(identifier, buffer, 6);
 		result = FUNC_RET_OK;
 	}
@@ -52,43 +51,43 @@
 	FUNCTION_RETURN return_value;
 	DWORD dwResult = GetLogicalDriveStrings(dwSize, szLogicalDrives);
 
-	if (dwResult > 0 && dwResult <= MAX_PATH)
-	{
+	if (dwResult > 0 && dwResult <= MAX_PATH) {
 		return_value = FUNC_RET_OK;
 		szSingleDrive = szLogicalDrives;
-		while (*szSingleDrive && ndrives < MAX_UNITS)
-		{
+		while (*szSingleDrive && ndrives < MAX_UNITS) {
 
 			// get the next drive
 			driveType = GetDriveType(szSingleDrive);
-			if (driveType == DRIVE_FIXED){
-				success = GetVolumeInformation(szSingleDrive, volName, MAX_PATH, &volSerial,
-					&FileMaxLen, &FileFlags, FileSysName, MAX_PATH);
+			if (driveType == DRIVE_FIXED) {
+				success = GetVolumeInformation(szSingleDrive, volName, MAX_PATH,
+						&volSerial, &FileMaxLen, &FileFlags, FileSysName,
+						MAX_PATH);
 				if (success) {
 					LOG_INFO("drive         : %s\n", szSingleDrive);
 					LOG_INFO("Volume Name   : %s\n", volName);
-					LOG_INFO("Volume Serial : 0x%x\n", volSerial);
-					LOG_DEBUG("Max file length : %d\n", FileMaxLen);
-					LOG_DEBUG("Filesystem      : %s\n", FileSysName);
-					if (diskInfos != NULL && * disk_info_size < ndrives){
+					LOG_INFO("Volume Serial : 0x%x\n", volSerial); LOG_DEBUG("Max file length : %d\n", FileMaxLen); LOG_DEBUG("Filesystem      : %s\n", FileSysName);
+					if (diskInfos != NULL && *disk_info_size < ndrives) {
 						strncpy(diskInfos[ndrives].device, volName, MAX_PATH);
-						strncpy(diskInfos[ndrives].label, FileSysName, MAX_PATH);
+						strncpy(diskInfos[ndrives].label, FileSysName,
+								MAX_PATH);
 						diskInfos[ndrives].id = ndrives;
-						diskInfos[ndrives].preferred = (strncmp(szSingleDrive, "C", 1) != 0);
+						diskInfos[ndrives].preferred = (strncmp(szSingleDrive,
+								"C", 1) != 0);
 
 					}
 					ndrives++;
-				}
-				else {
-					LOG_WARN("Unable to retrieve information of '%s'\n", szSingleDrive);
+				} else {
+					LOG_WARN("Unable to retrieve information of '%s'\n",
+							szSingleDrive);
 				}
 			}
-			LOG_INFO("This volume is not fixed : %s, type: %d\n", szSingleDrive);
+			LOG_INFO("This volume is not fixed : %s, type: %d\n",
+					szSingleDrive);
 			szSingleDrive += strlen(szSingleDrive) + 1;
 		}
 	}
 
-	if (*disk_info_size >= ndrives){
+	if (*disk_info_size >= ndrives) {
 		return_value = FUNC_RET_BUFFER_TOO_SMALL;
 	}
 	return return_value;
@@ -101,11 +100,10 @@
 
 	str2 = ipStringIn; /* save the pointer */
 	while (*str2) {
-		if (isdigit((unsigned char)*str2)) {
+		if (isdigit((unsigned char) *str2)) {
 			ipv4[index] *= 10;
 			ipv4[index] += *str2 - '0';
-		}
-		else {
+		} else {
 			index++;
 		}
 		str2++;
@@ -115,7 +113,8 @@
 
 //http://stackoverflow.com/questions/18046063/mac-address-using-c
 //TODO: count only interfaces with type (MIB_IF_TYPE_ETHERNET IF_TYPE_IEEE80211)
-FUNCTION_RETURN getAdapterInfos(OsAdapterInfo * adapterInfos, size_t * adapter_info_size) {
+FUNCTION_RETURN getAdapterInfos(OsAdapterInfo * adapterInfos,
+		size_t * adapter_info_size) {
 	DWORD dwStatus;
 	unsigned int i = 0;
 	FUNCTION_RETURN result;
@@ -124,22 +123,23 @@
 	DWORD dwBufLen = 20; //sizeof(AdapterInfo);         // Save the memory size of buffer
 
 	i = 3;
-	do{
-		pAdapterInfo = (PIP_ADAPTER_INFO)malloc(sizeof(IP_ADAPTER_INFO)*dwBufLen);
+	do {
+		pAdapterInfo = (PIP_ADAPTER_INFO) malloc(
+				sizeof(IP_ADAPTER_INFO) * dwBufLen);
 		dwStatus = GetAdaptersInfo(               // Call GetAdapterInfo
-			pAdapterInfo, // [out] buffer to receive data
-			&dwBufLen   // [in] size of receive data buffer
-			);
+				pAdapterInfo, // [out] buffer to receive data
+				&dwBufLen   // [in] size of receive data buffer
+				);
 		dwBufLen = dwBufLen / sizeof(IP_ADAPTER_INFO);
-		if (dwStatus != NO_ERROR){
+		if (dwStatus != NO_ERROR) {
 			free(pAdapterInfo);
 		}
 	} while (dwStatus == ERROR_BUFFER_OVERFLOW && i-- > 0);
 
-	if (dwStatus != ERROR_BUFFER_OVERFLOW){
+	if (dwStatus != ERROR_BUFFER_OVERFLOW) {
 		return FUNC_RET_ERROR;
 	}
-	if (adapterInfos == NULL || *adapter_info_size == 0){
+	if (adapterInfos == NULL || *adapter_info_size == 0) {
 		*adapter_info_size = dwBufLen;
 		free(pAdapterInfo);
 		return FUNC_RET_BUFFER_TOO_SMALL;
@@ -150,13 +150,16 @@
 	i = 0;
 	result = FUNC_RET_OK;
 	while (pAdapter) {
-		strncpy(adapterInfos[i].description, pAdapter->Description, min(sizeof(adapterInfos->description), MAX_ADAPTER_DESCRIPTION_LENGTH));
+		strncpy(adapterInfos[i].description, pAdapter->Description,
+				min(sizeof(adapterInfos->description),
+						MAX_ADAPTER_DESCRIPTION_LENGTH));
 		memcpy(adapterInfos[i].mac_address, pAdapter->Address, 8);
-		translate(pAdapter->IpAddressList.IpAddress.String, adapterInfos[i].ipv4_address);
+		translate(pAdapter->IpAddressList.IpAddress.String,
+				adapterInfos[i].ipv4_address);
 		adapterInfos[i].type = IFACE_TYPE_ETHERNET;
 		i++;
 		pAdapter = pAdapter->Next;
-		if (i == *adapter_info_size){
+		if (i == *adapter_info_size) {
 			result = FUNC_RET_BUFFER_TOO_SMALL;
 			break;
 		}
@@ -166,37 +169,37 @@
 	return result;
 }
 FUNCTION_RETURN getModuleName(char buffer[MAX_PATH]) {
-	FUNCTION_RETURN result=FUNC_RET_OK;
+	FUNCTION_RETURN result = FUNC_RET_OK;
 	DWORD wres = GetModuleFileName(NULL, buffer, MAX_PATH);
-	if (wres == 0){
+	if (wres == 0) {
 		result = FUNC_RET_ERROR;
 	}
 	return result;
 }
 
-static void printHash(HCRYPTHASH* hHash){
-	BYTE         *pbHash;
-	DWORD        dwHashLen;
-	DWORD        dwHashLenSize = sizeof(DWORD); 
+static void printHash(HCRYPTHASH* hHash) {
+	BYTE *pbHash;
+	DWORD dwHashLen;
+	DWORD dwHashLenSize = sizeof(DWORD);
 	char* hashStr;
 	int i;
 
-	if (CryptGetHashParam(*hHash,HP_HASHSIZE,(BYTE *)&dwHashLen, &dwHashLenSize, 0))
-	{
-		pbHash = (BYTE*)malloc(dwHashLen);
-		hashStr = (char*)malloc(dwHashLen*2 +1);
-		if (CryptGetHashParam(*hHash,HP_HASHVAL,pbHash,	&dwHashLen,	0))	{
-			for (i = 0; i < dwHashLen; i++)	{
+	if (CryptGetHashParam(*hHash, HP_HASHSIZE, (BYTE *) &dwHashLen,
+			&dwHashLenSize, 0)) {
+		pbHash = (BYTE*) malloc(dwHashLen);
+		hashStr = (char*) malloc(dwHashLen * 2 + 1);
+		if (CryptGetHashParam(*hHash, HP_HASHVAL, pbHash, &dwHashLen, 0)) {
+			for (i = 0; i < dwHashLen; i++) {
 				sprintf(&hashStr[i * 2], "%02x", pbHash[i]);
-			}
-			LOG_DEBUG("Hash to verify: %s", hashStr);
+			} LOG_DEBUG("Hash to verify: %s", hashStr);
 		}
 		free(pbHash);
 		free(hashStr);
 	}
 }
 
-FUNCTION_RETURN verifySignature(const char* stringToVerify,	const char* signatureB64) {
+FUNCTION_RETURN verifySignature(const char* stringToVerify,
+		const char* signatureB64) {
 	//--------------------------------------------------------------------
 	// Declare variables.
 	//
@@ -218,33 +221,20 @@
 	//--------------------------------------------------------------------
 	// Acquire a handle to the CSP.
 
-	if (!CryptAcquireContext(
-		&hProv,
-		NULL,
-		MS_ENHANCED_PROV,
-		PROV_RSA_FULL,
-		CRYPT_VERIFYCONTEXT))
-	{
+	if (!CryptAcquireContext(&hProv,
+	NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
 		// If the key container cannot be opened, try creating a new
 		// container by specifying a container name and setting the 
 		// CRYPT_NEWKEYSET flag.
 		LOG_INFO("Error in AcquireContext 0x%08x \n", GetLastError());
-		if (NTE_BAD_KEYSET == GetLastError())
-		{
-			if (!CryptAcquireContext(
-				&hProv,
-				"license++verify",
-				MS_ENHANCED_PROV,
-				PROV_RSA_FULL,
-				CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT))
-			{
-				LOG_ERROR("Error in AcquireContext 0x%08x \n",
-					GetLastError());
+		if (NTE_BAD_KEYSET == GetLastError()) {
+			if (!CryptAcquireContext(&hProv, "license++verify",
+					MS_ENHANCED_PROV, PROV_RSA_FULL,
+					CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT)) {
+				LOG_ERROR("Error in AcquireContext 0x%08x \n", GetLastError());
 				return FUNC_RET_ERROR;
 			}
-		}
-		else
-		{
+		} else {
 			LOG_ERROR(" Error in AcquireContext 0x%08x \n", GetLastError());
 			return FUNC_RET_ERROR;
 		}
@@ -254,25 +244,20 @@
 	// BYTE array into the key container. The function returns a 
 	// pointer to an HCRYPTKEY variable that contains the handle of
 	// the imported key.
-	if (!CryptImportKey(hProv, &pubKey[0], sizeof(pubKey), 0, 0, &hKey))
-	{
-		LOG_ERROR("Error 0x%08x in importing the PublicKey \n",
-			GetLastError());
+	if (!CryptImportKey(hProv, &pubKey[0], sizeof(pubKey), 0, 0, &hKey)) {
+		LOG_ERROR("Error 0x%08x in importing the PublicKey \n", GetLastError());
 		return FUNC_RET_ERROR;
 	}
 
-	if (CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash))
-	{
+	if (CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash)) {
 		LOG_DEBUG("Hash object created.");
-	}
-	else
-	{
+	} else {
 		LOG_ERROR("Error in hash creation 0x%08x ", GetLastError());
-		CryptReleaseContext(hProv,0);
+		CryptReleaseContext(hProv, 0);
 		return FUNC_RET_ERROR;
 	}
 
-	if (!CryptHashData(hHash, stringToVerify, strlen(stringToVerify), 0)){
+	if (!CryptHashData(hHash, stringToVerify, strlen(stringToVerify), 0)) {
 		LOG_ERROR("Error in hashing data 0x%08x ", GetLastError());
 		CryptDestroyHash(hHash);
 		CryptReleaseContext(hProv, 0);
@@ -284,8 +269,7 @@
 #endif
 	sigBlob = unbase64(signatureB64, strlen(signatureB64), &dwSigLen);
 	LOG_DEBUG("raw signature lenght %d", dwSigLen);
-	if (!CryptVerifySignature(hHash, sigBlob, dwSigLen, hKey, NULL, 0))
-	{
+	if (!CryptVerifySignature(hHash, sigBlob, dwSigLen, hKey, NULL, 0)) {
 		LOG_ERROR("Signature not validated!  0x%08x ", GetLastError());
 		free(sigBlob);
 		CryptDestroyHash(hHash);
diff --git a/src/library/os/win/os-win.cpp b/src/library/os/win/os-win.cpp
deleted file mode 100644
index 654dc06..0000000
--- a/src/library/os/win/os-win.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-#include <string>
-#include "../os-cpp.h"
-
-
-namespace license {
-
-using namespace std;
-
-
-VIRTUALIZATION getVirtualization() {
-//http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html
-//
-//bool rc = true;
-	/*__asm__ (
-	 "push   %edx\n"
-	 "push   %ecx\n"
-	 "push   %ebx\n"
-	 "mov    %eax, 'VMXh'\n"
-	 "mov    %ebx, 0\n" // any value but not the MAGIC VALUE
-	 "mov    %ecx, 10\n"// get VMWare version
-	 "mov    %edx, 'VX'\n"// port number
-	 "in     %eax, dx\n"// read port on return EAX returns the VERSION
-	 "cmp    %ebx, 'VMXh'\n"// is it a reply from VMWare?
-	 "setz   [rc] \n"// set return value
-	 "pop    %ebx \n"
-	 "pop    %ecx \n"
-	 "pop    %edx \n"
-	 );*/
-
-	return NONE;
-}
-
-}
\ No newline at end of file
diff --git a/src/scratch/LicenseSigner_linux.cpp b/src/scratch/linux/LicenseSigner_linux.cpp
similarity index 100%
rename from src/scratch/LicenseSigner_linux.cpp
rename to src/scratch/linux/LicenseSigner_linux.cpp
diff --git a/src/scratch/bootstrap_linux.cpp b/src/scratch/linux/bootstrap_linux.cpp
similarity index 100%
rename from src/scratch/bootstrap_linux.cpp
rename to src/scratch/linux/bootstrap_linux.cpp
diff --git a/src/scratch/linux/os-linux.cpp b/src/scratch/linux/os-linux.cpp
new file mode 100644
index 0000000..d9e8662
--- /dev/null
+++ b/src/scratch/linux/os-linux.cpp
@@ -0,0 +1,64 @@
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE     /* To get defns of NI_MAXSERV and NI_MAXHOST */
+#endif
+#include <arpa/inet.h>
+#include <sys/socket.h>
+#include <netdb.h>
+#include <ifaddrs.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <linux/if_link.h>
+#include <sys/socket.h>
+#include <netpacket/packet.h>
+
+#include <paths.h>
+
+#include <stdlib.h>
+#include <cstring>
+#include <string>
+#include <system_error>
+#include <unistd.h>
+#include <sstream>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include "../os-cpp.h"
+#include "public-key.h"
+
+#include <openssl/evp.h>
+#include <openssl/bio.h>
+#include <openssl/pem.h>
+#include <openssl/err.h>
+
+namespace license {
+
+using namespace std;
+
+
+
+
+
+VIRTUALIZATION getVirtualization() {
+//http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html
+//
+//bool rc = true;
+	/*__asm__ (
+	 "push   %edx\n"
+	 "push   %ecx\n"
+	 "push   %ebx\n"
+	 "mov    %eax, 'VMXh'\n"
+	 "mov    %ebx, 0\n" // any value but not the MAGIC VALUE
+	 "mov    %ecx, 10\n"// get VMWare version
+	 "mov    %edx, 'VX'\n"// port number
+	 "in     %eax, dx\n"// read port on return EAX returns the VERSION
+	 "cmp    %ebx, 'VMXh'\n"// is it a reply from VMWare?
+	 "setz   [rc] \n"// set return value
+	 "pop    %ebx \n"
+	 "pop    %ecx \n"
+	 "pop    %edx \n"
+	 );*/
+
+	return NONE;
+}
+
+}
diff --git a/src/scratch/win/Copy of Main.cpp b/src/scratch/win/Copy of Main.cpp
new file mode 100644
index 0000000..deb31ac
--- /dev/null
+++ b/src/scratch/win/Copy of Main.cpp
@@ -0,0 +1,125 @@
+#include <stdio.h>
+#include "../base_lib/CryptoHelper.h"
+#include <string>
+#include <stdlib.h>
+#include <iostream> 
+
+using namespace std;
+namespace license {
+
+void write_pubkey_file(string public_fname, BYTE *pbPublicKey,
+		DWORD dwPublicKeySize) {
+	FILE* fp = fopen(public_fname.c_str(), "w");
+	fprintf(fp, "//file generated by bootstrap.cpp, do not edit.\n\n");
+	fprintf(fp, "#ifndef PUBLIC_KEY_H_\n#define PUBLIC_KEY_H_\n");
+	fprintf(fp, "static BYTE PUBLIC_KEY[] = {");
+	for (int i = 0; i < dwPublicKeySize; i++) {
+		if (i != 0) {
+			fprintf(fp, ",");
+		}
+		if (i % 15 == 0) {
+			fprintf(fp, "\n        ");
+		}
+		fprintf(fp, "%d", pbPublicKey[i]);
+	}
+	fprintf(fp, "\n};\n\n");
+	int random = rand() % 1000;
+	fprintf(fp, "#define SHARED_RANDOM %d;\n", random);
+	fprintf(fp, "#endif\n");
+	fclose(fp);
+}
+
+void write_privkey_file(string private_fname, BYTE *privateKey,
+		DWORD dwPrivateKeySize) {
+	FILE* fp = fopen(private_fname.c_str(), "w");
+	fprintf(fp, "//file generated by bootstrap.cpp, do not edit.\n\n");
+	fprintf(fp, "#ifndef PRIVATE_KEY_H_\n#define PRIVATE_KEY_H_\n");
+	fprintf(fp, "static BYTE PRIVATE_KEY[] = {");
+	for (int i = 0; i < dwPrivateKeySize; i++) {
+		if (i != 0) {
+			fprintf(fp, ",");
+		}
+		if (i % 15 == 0) {
+			fprintf(fp, "\n        ");
+		}
+		fprintf(fp, "%d", privateKey[i]);
+	}
+	fprintf(fp, "\n};\n\n");
+	fprintf(fp, "#endif\n");
+	fclose(fp);
+}
+
+void generatePk(string private_include, string public_include) {
+	unique_ptr<CryptoHelper> cryptoHlpr = CryptoHelper.getInstance();
+	BYTE *pbPublicKey = NULL, *pbPrivateKey = NULL;
+	DWORD dwPublicKeySize = 0, dwPrivateKeySize = 0;
+	HRESULT hr = S_OK;
+	// Get the key container context.
+	if (FAILED(hr = cryptoHlpr.AcquireContext(_T("TestContainer")))) {
+// Call FormatMessage to display the error returned in hr.
+		return;
+	}
+	// Generate the public/private key pair.
+	if (FAILED(hr = cryptoHlpr.GenerateKeyPair())) {
+// Call FormatMessage to display the error returned in hr.
+		return;
+	}
+	// Export out the public key blob.
+	if (FAILED(
+			hr = cryptoHlpr.ExportPublicKey(&pbPublicKey, dwPublicKeySize))) {
+// Call FormatMessage to display the error returned in hr.
+		cerr << "error exporting pubkey" << endl;
+		return;
+	} else {
+		write_pubkey_file(public_include, pbPublicKey, dwPublicKeySize);
+	}
+	// Print out the public key to console as a
+	// hexadecimal string.
+	wprintf(L"\n\nPublicKey = \"");
+	for (DWORD i = 0; i < dwPublicKeySize; i++) {
+		wprintf(L"%02x", pbPublicKey[i]);
+	}
+	wprintf(L"\"\n");
+	// Export out the private key blob.
+	if (FAILED(cryptoHlpr.ExportPrivateKey(&pbPrivateKey, dwPrivateKeySize))) {
+		cerr << "Error exporting private key." << endl;
+		return;
+	} else {
+		write_privkey_file(private_include, pbPrivateKey, dwPrivateKeySize);
+	}
+	// Print out the private key to console as a
+	// hexadecimal string.
+	wprintf(L"\n\nPrivateKey = \"");
+	for (DWORD i = 0; i < dwPrivateKeySize; i++) {
+		wprintf(L"%02x", pbPrivateKey[i]);
+	}
+	wprintf(L"\"\n");
+	// Delete the public key blob allocated by the
+// ExportPublicKey method.
+	if (pbPublicKey)
+		delete[] pbPublicKey;
+	// Delete the private key blob allocated by the
+// ExportPrivateKey method.
+	if (pbPrivateKey)
+		delete[] pbPrivateKey;
+	return;
+}
+}
+
+int main(int argc, char** argv) {
+
+	if (argc != 3) {
+		//print_usage();
+		exit(2);
+	} else {
+		printf("********************************************\n");
+		printf("*  Bootstrap!!!                            *\n");
+		printf("********************************************\n");
+
+	}
+	string private_fname = string(argv[1]);
+	string public_fname(argv[2]);
+
+	license::generatePk(private_fname, public_fname);
+	return 0;
+}
diff --git a/src/tools/base_lib/win/CryptoHelper.cpp b/src/tools/base_lib/win/CryptoHelper.cpp
deleted file mode 100644
index 44a06fe..0000000
--- a/src/tools/base_lib/win/CryptoHelper.cpp
+++ /dev/null
@@ -1,215 +0,0 @@
-#include "../CryptoHelper.h"
-// The RSA public-key key exchange algorithm
-#define ENCRYPT_ALGORITHM         CALG_RSA_SIGN
-// The high order WORD 0x0200 (decimal 512)
-// determines the key length in bits.
-#define KEYLENGTH                 0x02000000
-//--------------------------------------------------------------------
-// The constructor initializes the member variables
-// to NULL.
-//--------------------------------------------------------------------
-CryptoHelper::CryptoHelper()
-{
-       m_hCryptProv = NULL;
-       m_hCryptKey   = NULL;
-}
-//--------------------------------------------------------------------
-// The destructor releases the handles acquired
-// when an object goes out of scope.
-//--------------------------------------------------------------------
-CryptoHelper::~CryptoHelper()
-{
-       if (m_hCryptProv)
-       {
-              CryptReleaseContext(m_hCryptProv,0);
-              m_hCryptProv = NULL;
-       }
-       if (m_hCryptKey)
-              m_hCryptKey = NULL;
-}
-
-//--------------------------------------------------------------------
-// This method calls the CryptAcquireContext function
-// to get a handle to a key container owned by the the
-// Microsoft Enhanced Cryptographic Provider.
-//--------------------------------------------------------------------
-HRESULT CryptoHelper::AcquireContext(LPCTSTR wszContainerName)
-{
-       HRESULT       hr = S_OK;
-       DWORD         dwErrCode;
-// Release a previously acquired handle to the key container.
-if (m_hCryptProv != NULL)
-       {
-              CryptReleaseContext(m_hCryptProv,0);
-              m_hCryptProv = NULL;
-       }
-// Release a previously acquired handle to key-pair.
-       if (m_hCryptKey != NULL)
-              m_hCryptKey = NULL;
-       // Attempt to acquire a context and a key container.
-// The context will use Microsoft Enhanced Cryptographic
-       // Provider for the RSA_FULL provider type.
-       if(!CryptAcquireContext(&m_hCryptProv,
-                               wszContainerName,
-                               MS_ENHANCED_PROV,
-                               PROV_RSA_FULL,
-    0))
-       {
-         // An error occurred in acquiring the context. This could mean
-         // that the key container requested does not exist. In this case,
-        // the function can be called again to attempt to create a new key
-              // container.
-              if (GetLastError() == NTE_BAD_KEYSET)
-              {
-                     if(!CryptAcquireContext(&m_hCryptProv,
-                                            wszContainerName,
-                                            MS_ENHANCED_PROV,   PROV_RSA_FULL,
-                                            CRYPT_NEWKEYSET))
-                     {
-                           dwErrCode = GetLastError();
-                            return HRESULT_FROM_WIN32(dwErrCode);
-                     }
-              }
-              else
-              {
-                     dwErrCode = GetLastError();
-                     return HRESULT_FROM_WIN32(dwErrCode);
-              }
-       }
-       return hr;
-}
-//--------------------------------------------------------------------
-
-// This method calls the CryptGenKey function to get a handle to an
-
-// exportable key-pair. The key-pair is  generated with the RSA public-key
-// key exchange algorithm using Microsoft Enhanced Cryptographic Provider.
-//--------------------------------------------------------------------
-HRESULT CryptoHelper::GenerateKeyPair()
-{
-       HRESULT       hr = S_OK;
-       DWORD         dwErrCode;
-       // If the handle to key container is NULL, fail.
-if (m_hCryptProv == NULL)
-              return E_FAIL;
-// Release a previously acquired handle to key-pair.
-if (m_hCryptKey)
-              m_hCryptKey = NULL;
-       // Call the CryptGenKey method to get a handle
-       // to a new exportable key-pair.
-if(!CryptGenKey(m_hCryptProv,
-                ENCRYPT_ALGORITHM,
-   KEYLENGTH | CRYPT_EXPORTABLE,
-   &m_hCryptKey))
-       {
-              dwErrCode = GetLastError();
-              return HRESULT_FROM_WIN32(dwErrCode);
-       }
-       return hr;
-}
-//--------------------------------------------------------------------
-// This method calls the CryptExportKey function to get the Public key
-// in a byte array. The byte array is allocated on the heap and the size
-// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
-//--------------------------------------------------------------------
-HRESULT CryptoHelper::ExportPublicKey(BYTE **ppPublicKey, DWORD &cbKeySize)
-{
-       HRESULT hr = S_OK;
-       DWORD    dwErrCode;
-       DWORD dwBlobLen;
-       BYTE *pbKeyBlob = NULL;
-       // If the handle to key container is NULL, fail.
-       if (m_hCryptKey == NULL)
-              return E_FAIL;
-       // This call here determines the length of the key
-       // blob.
-       if(!CryptExportKey(
-                 m_hCryptKey,
-                 NULL,
-                 PUBLICKEYBLOB,
-                 0,
-                 NULL,
-                 &dwBlobLen))
-       {
-              dwErrCode = GetLastError();
-              return HRESULT_FROM_WIN32(dwErrCode);
-       }
-       // Allocate memory for the pbKeyBlob.
-       if((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
-       {
-              return E_OUTOFMEMORY;
-       }
-       // Do the actual exporting into the key BLOB.
-       if(!CryptExportKey(
-                 m_hCryptKey,
-                 NULL,
-                 PUBLICKEYBLOB,
-                 0,
-                 pbKeyBlob,
-                 &dwBlobLen))
-       {
-              delete pbKeyBlob;
-              dwErrCode = GetLastError();
-              return HRESULT_FROM_WIN32(dwErrCode);
-       }
-       else
-       {
-               *ppPublicKey = pbKeyBlob;
-               cbKeySize = dwBlobLen;
-       }
-       return hr;
-}
-//--------------------------------------------------------------------
-// This method calls the CryptExportKey function to get the Private key
-// in a byte array. The byte array is allocated on the heap and the size
-// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
-//--------------------------------------------------------------------
-HRESULT CryptoHelper::ExportPrivateKey(BYTE **ppPrivateKey, DWORD &cbKeySize)
-{
-       HRESULT       hr = S_OK;
-       DWORD         dwErrCode;
-       DWORD dwBlobLen;
-       BYTE *pbKeyBlob;
-       // If the handle to key container is NULL, fail.
-       if (m_hCryptKey == NULL)
-              return E_FAIL;
-       // This call here determines the length of the key
-       // blob.
-       if(!CryptExportKey(
-                 m_hCryptKey,
-                 NULL,
-                 PRIVATEKEYBLOB,
-                 0,
-                 NULL,
-                 &dwBlobLen))
-       {
-              dwErrCode = GetLastError();
-              return HRESULT_FROM_WIN32(dwErrCode);
-       }
-       // Allocate memory for the pbKeyBlob.
-       if((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
-       {
-              return E_OUTOFMEMORY;
-       }
-
-       // Do the actual exporting into the key BLOB.
-       if(!CryptExportKey(
-                 m_hCryptKey,
-                 NULL,
-                 PRIVATEKEYBLOB,
-                 0,
-                 pbKeyBlob,
-                 &dwBlobLen))
-       {
-              delete pbKeyBlob;
-              dwErrCode = GetLastError();
-              return HRESULT_FROM_WIN32(dwErrCode);
-       }
-       else
-       {
-               *ppPrivateKey = pbKeyBlob;
-               cbKeySize = dwBlobLen;
-       }
-       return hr;
-}
-
diff --git a/src/tools/base_lib/win/CryptoHelperWindows.cpp b/src/tools/base_lib/win/CryptoHelperWindows.cpp
index e2d8cff..8669926 100644
--- a/src/tools/base_lib/win/CryptoHelperWindows.cpp
+++ b/src/tools/base_lib/win/CryptoHelperWindows.cpp
@@ -17,438 +17,366 @@
 
 namespace license {
 
-	CryptoHelperWindows::CryptoHelperWindows() {
-		m_hCryptProv = NULL;
-		m_hCryptKey = NULL;
-		if (!CryptAcquireContext(
-			&m_hCryptProv,
-			"license++sign",
-			MS_ENHANCED_PROV,
-			PROV_RSA_FULL,
-			0))
-		{
-			// If the key container cannot be opened, try creating a new
-			// container by specifying a container name and setting the 
-			// CRYPT_NEWKEYSET flag.
-			printf("Error in AcquireContext 0x%08x \n", GetLastError());
-			if (NTE_BAD_KEYSET == GetLastError())
-			{
-				if (!CryptAcquireContext(
-					&m_hCryptProv,
-					"license++sign",
-					MS_ENHANCED_PROV,
-					PROV_RSA_FULL,
-					CRYPT_NEWKEYSET))
-				{
-					printf("Error in AcquireContext 0x%08x \n",
-						GetLastError());
-					throw logic_error("");
-				}
-			}
-			else
-			{
-				printf(" Error in AcquireContext 0x%08x \n", GetLastError());
+CryptoHelperWindows::CryptoHelperWindows() {
+	m_hCryptProv = NULL;
+	m_hCryptKey = NULL;
+	if (!CryptAcquireContext(&m_hCryptProv, "license++sign", MS_ENHANCED_PROV,
+			PROV_RSA_FULL, 0)) {
+		// If the key container cannot be opened, try creating a new
+		// container by specifying a container name and setting the
+		// CRYPT_NEWKEYSET flag.
+		printf("Error in AcquireContext 0x%08x \n", GetLastError());
+		if (NTE_BAD_KEYSET == GetLastError()) {
+			if (!CryptAcquireContext(&m_hCryptProv, "license++sign",
+					MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
+				printf("Error in AcquireContext 0x%08x \n", GetLastError());
 				throw logic_error("");
 			}
-		}
-
-	}
-
-
-	/**
-	This method calls the CryptGenKey function to get a handle to an
-
-	exportable key-pair. The key-pair is  generated with the RSA public-key
-	key exchange algorithm using Microsoft Enhanced Cryptographic Provider.
-	*/
-	void CryptoHelperWindows::generateKeyPair()
-	{
-		HRESULT       hr = S_OK;
-		DWORD         dwErrCode;
-		// If the handle to key container is NULL, fail.
-		if (m_hCryptProv == NULL)
-			throw logic_error("Cryptocontext not correctly initialized");
-		// Release a previously acquired handle to key-pair.
-		if (m_hCryptKey)
-			m_hCryptKey = NULL;
-		// Call the CryptGenKey method to get a handle
-		// to a new exportable key-pair.
-		if (!CryptGenKey(m_hCryptProv,
-			ENCRYPT_ALGORITHM,
-			KEYLENGTH | CRYPT_EXPORTABLE,
-			&m_hCryptKey))
-		{
-			dwErrCode = GetLastError();
-			throw logic_error(string("Error generating keys ") + to_string(dwErrCode));
+		} else {
+			printf(" Error in AcquireContext 0x%08x \n", GetLastError());
+			throw logic_error("");
 		}
 	}
 
-	/* This method calls the CryptExportKey function to get the Public key
-	 in a string suitable for C source inclusion.
-	 */
-	const string CryptoHelperWindows::exportPublicKey() const
-	{
-		HRESULT hr = S_OK;
-		DWORD    dwErrCode;
-		DWORD dwBlobLen;
-		BYTE *pbKeyBlob = NULL;
-		stringstream ss;
-		// If the handle to key container is NULL, fail.
-		if (m_hCryptKey == NULL)
-			throw logic_error("call GenerateKey first.");
-		// This call here determines the length of the key
-		// blob.
-		if (!CryptExportKey(
-			m_hCryptKey,
-			NULL,
-			PUBLICKEYBLOB,
-			0,
-			NULL,
-			&dwBlobLen))
-		{
-			dwErrCode = GetLastError();
-			throw logic_error(string("Error calculating size of public key ") + to_string(dwErrCode));
-		}
-		// Allocate memory for the pbKeyBlob.
-		if ((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
-		{
-			throw logic_error(string("Out of memory exporting public key "));
-		}
-		// Do the actual exporting into the key BLOB.
-		if (!CryptExportKey(
-			m_hCryptKey,
-			NULL,
-			PUBLICKEYBLOB,
-			0,
-			pbKeyBlob,
-			&dwBlobLen))
-		{
-			delete pbKeyBlob;
-			dwErrCode = GetLastError();
-			throw logic_error(string("Error exporting public key ") + to_string(dwErrCode));
-		}
-		else
-		{
-			ss << "\t";
-			for (unsigned int i = 0; i < dwBlobLen; i++){
-				if (i != 0){
-					ss << ", ";
-					if (i % 10 == 0){
-						ss << "\\" << endl << "\t";
-					}
+}
+
+/**
+ This method calls the CryptGenKey function to get a handle to an
+
+ exportable key-pair. The key-pair is  generated with the RSA public-key
+ key exchange algorithm using Microsoft Enhanced Cryptographic Provider.
+ */
+void CryptoHelperWindows::generateKeyPair() {
+	HRESULT hr = S_OK;
+	DWORD dwErrCode;
+	// If the handle to key container is NULL, fail.
+	if (m_hCryptProv == NULL)
+		throw logic_error("Cryptocontext not correctly initialized");
+	// Release a previously acquired handle to key-pair.
+	if (m_hCryptKey)
+		m_hCryptKey = NULL;
+	// Call the CryptGenKey method to get a handle
+	// to a new exportable key-pair.
+	if (!CryptGenKey(m_hCryptProv,
+	ENCRYPT_ALGORITHM,
+	KEYLENGTH | CRYPT_EXPORTABLE, &m_hCryptKey)) {
+		dwErrCode = GetLastError();
+		throw logic_error(
+				string("Error generating keys ") + to_string(dwErrCode));
+	}
+}
+
+/* This method calls the CryptExportKey function to get the Public key
+ in a string suitable for C source inclusion.
+ */
+const string CryptoHelperWindows::exportPublicKey() const {
+	HRESULT hr = S_OK;
+	DWORD dwErrCode;
+	DWORD dwBlobLen;
+	BYTE *pbKeyBlob = NULL;
+	stringstream ss;
+	// If the handle to key container is NULL, fail.
+	if (m_hCryptKey == NULL)
+		throw logic_error("call GenerateKey first.");
+	// This call here determines the length of the key
+	// blob.
+	if (!CryptExportKey(m_hCryptKey,
+	NULL, PUBLICKEYBLOB, 0,
+	NULL, &dwBlobLen)) {
+		dwErrCode = GetLastError();
+		throw logic_error(
+				string("Error calculating size of public key ")
+						+ to_string(dwErrCode));
+	}
+	// Allocate memory for the pbKeyBlob.
+	if ((pbKeyBlob = new BYTE[dwBlobLen]) == NULL) {
+		throw logic_error(string("Out of memory exporting public key "));
+	}
+	// Do the actual exporting into the key BLOB.
+	if (!CryptExportKey(m_hCryptKey,
+	NULL, PUBLICKEYBLOB, 0, pbKeyBlob, &dwBlobLen)) {
+		delete pbKeyBlob;
+		dwErrCode = GetLastError();
+		throw logic_error(
+				string("Error exporting public key ") + to_string(dwErrCode));
+	} else {
+		ss << "\t";
+		for (unsigned int i = 0; i < dwBlobLen; i++) {
+			if (i != 0) {
+				ss << ", ";
+				if (i % 10 == 0) {
+					ss << "\\" << endl << "\t";
 				}
-				ss << to_string(pbKeyBlob[i]);
 			}
-			delete pbKeyBlob;
+			ss << to_string(pbKeyBlob[i]);
 		}
-		return ss.str();
+		delete pbKeyBlob;
+	}
+	return ss.str();
+}
+
+CryptoHelperWindows::~CryptoHelperWindows() {
+	if (m_hCryptProv) {
+		CryptReleaseContext(m_hCryptProv, 0);
+		m_hCryptProv = NULL;
+	}
+	if (m_hCryptKey)
+		m_hCryptKey = NULL;
+}
+
+//--------------------------------------------------------------------
+// This method calls the CryptExportKey function to get the Private key
+// in a byte array. The byte array is allocated on the heap and the size
+// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
+//--------------------------------------------------------------------
+const string CryptoHelperWindows::exportPrivateKey() const {
+	HRESULT hr = S_OK;
+	DWORD dwErrCode;
+	DWORD dwBlobLen;
+	BYTE *pbKeyBlob;
+	stringstream ss;
+	// If the handle to key container is NULL, fail.
+	if (m_hCryptKey == NULL)
+		throw logic_error(string("call GenerateKey first."));
+	// This call here determines the length of the key
+	// blob.
+	if (!CryptExportKey(m_hCryptKey,
+	NULL, PRIVATEKEYBLOB, 0,
+	NULL, &dwBlobLen)) {
+		dwErrCode = GetLastError();
+		throw logic_error(
+				string("Error calculating size of private key ")
+						+ to_string(dwErrCode));
+	}
+	// Allocate memory for the pbKeyBlob.
+	if ((pbKeyBlob = new BYTE[dwBlobLen]) == NULL) {
+		throw logic_error(string("Out of memory exporting private key "));
 	}
 
-	CryptoHelperWindows::~CryptoHelperWindows() {
-		if (m_hCryptProv)
-		{
-			CryptReleaseContext(m_hCryptProv, 0);
-			m_hCryptProv = NULL;
-		}
-		if (m_hCryptKey)
-			m_hCryptKey = NULL;
-	}
-
-	//--------------------------------------------------------------------
-	// This method calls the CryptExportKey function to get the Private key
-	// in a byte array. The byte array is allocated on the heap and the size
-	// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
-	//--------------------------------------------------------------------
-	const string CryptoHelperWindows::exportPrivateKey() const
-	{
-		HRESULT       hr = S_OK;
-		DWORD         dwErrCode;
-		DWORD dwBlobLen;
-		BYTE *pbKeyBlob;
-		stringstream ss;
-		// If the handle to key container is NULL, fail.
-		if (m_hCryptKey == NULL)
-			throw logic_error(string("call GenerateKey first."));
-		// This call here determines the length of the key
-		// blob.
-		if (!CryptExportKey(
-			m_hCryptKey,
-			NULL,
-			PRIVATEKEYBLOB,
-			0,
-			NULL,
-			&dwBlobLen))
-		{
-			dwErrCode = GetLastError();
-			throw logic_error(string("Error calculating size of private key ") + to_string(dwErrCode));
-		}
-		// Allocate memory for the pbKeyBlob.
-		if ((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
-		{
-			throw logic_error(string("Out of memory exporting private key "));
-		}
-
-		// Do the actual exporting into the key BLOB.
-		if (!CryptExportKey(
-			m_hCryptKey,
-			NULL,
-			PRIVATEKEYBLOB,
-			0,
-			pbKeyBlob,
-			&dwBlobLen))
-		{
-			delete pbKeyBlob;
-			dwErrCode = GetLastError();
-			throw logic_error(string("Error exporting private key ") + to_string(dwErrCode));
-		}
-		else
-		{
-			ss << "\t";
-			for (unsigned int i = 0; i < dwBlobLen; i++){
-				if (i != 0){
-					ss << ", ";
-					if (i % 15 == 0){
-						ss << "\\" << endl << "\t";
-					}
+	// Do the actual exporting into the key BLOB.
+	if (!CryptExportKey(m_hCryptKey,
+	NULL, PRIVATEKEYBLOB, 0, pbKeyBlob, &dwBlobLen)) {
+		delete pbKeyBlob;
+		dwErrCode = GetLastError();
+		throw logic_error(
+				string("Error exporting private key ") + to_string(dwErrCode));
+	} else {
+		ss << "\t";
+		for (unsigned int i = 0; i < dwBlobLen; i++) {
+			if (i != 0) {
+				ss << ", ";
+				if (i % 15 == 0) {
+					ss << "\\" << endl << "\t";
 				}
-				ss << to_string(pbKeyBlob[i]);
 			}
-			delete pbKeyBlob;
+			ss << to_string(pbKeyBlob[i]);
 		}
-		return ss.str();
+		delete pbKeyBlob;
+	}
+	return ss.str();
+}
+
+void CryptoHelperWindows::printHash(HCRYPTHASH* hHash) const {
+	BYTE *pbHash;
+	DWORD dwHashLen;
+	DWORD dwHashLenSize = sizeof(DWORD);
+	char* hashStr;
+	int i;
+
+	if (CryptGetHashParam(*hHash, HP_HASHSIZE, (BYTE *) &dwHashLen,
+			&dwHashLenSize, 0)) {
+		pbHash = (BYTE*) malloc(dwHashLen);
+		hashStr = (char*) malloc(dwHashLen * 2 + 1);
+		if (CryptGetHashParam(*hHash, HP_HASHVAL, pbHash, &dwHashLen, 0)) {
+			for (i = 0; i < dwHashLen; i++) {
+				sprintf(&hashStr[i * 2], "%02x", pbHash[i]);
+			}
+			printf("hash To be signed: %s \n", hashStr);
+		}
+		free(pbHash);
+		free(hashStr);
+	}
+}
+
+const string CryptoHelperWindows::signString(const void* privateKey,
+		size_t pklen, const string& license) const {
+	BYTE *pbBuffer = (BYTE *) license.c_str();
+	DWORD dwBufferLen = strlen((char *) pbBuffer);
+	HCRYPTHASH hHash;
+
+	HCRYPTKEY hKey;
+	BYTE *pbKeyBlob;
+	BYTE *pbSignature;
+	DWORD dwSigLen;
+	DWORD dwBlobLen;
+	DWORD strLen;
+
+	//-------------------------------------------------------------------
+	// Acquire a cryptographic provider context handle.
+
+	if (!CryptImportKey(m_hCryptProv, (const BYTE *) privateKey, pklen, 0, 0,
+			&hKey)) {
+		throw logic_error(
+				string("Error in importing the PrivateKey ")
+						+ to_string(GetLastError()));
 	}
 
-	void CryptoHelperWindows::printHash(HCRYPTHASH* hHash) const {
-		BYTE         *pbHash;
-		DWORD        dwHashLen;
-		DWORD        dwHashLenSize = sizeof(DWORD);
-		char* hashStr;
-		int i;
+	//-------------------------------------------------------------------
+	// Create the hash object.
 
-		if (CryptGetHashParam(*hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwHashLenSize, 0))
-		{
-			pbHash = (BYTE*)malloc(dwHashLen);
-			hashStr = (char*)malloc(dwHashLen * 2 + 1);
-			if (CryptGetHashParam(*hHash, HP_HASHVAL, pbHash, &dwHashLen, 0))	{
-				for (i = 0; i < dwHashLen; i++)	{
-					sprintf(&hashStr[i * 2], "%02x", pbHash[i]);
-				}
-				printf("hash To be signed: %s \n", hashStr);
-			}
-			free(pbHash);
-			free(hashStr);
-		}
-	}
-
-	const string CryptoHelperWindows::signString(const void* privateKey, size_t pklen,
-		const string& license) const{
-		BYTE *pbBuffer = (BYTE *)license.c_str();
-		DWORD dwBufferLen = strlen((char *)pbBuffer);
-		HCRYPTHASH hHash;
-
-		HCRYPTKEY hKey;
-		BYTE *pbKeyBlob;
-		BYTE *pbSignature;
-		DWORD dwSigLen;
-		DWORD dwBlobLen;
-		DWORD strLen;
-
-
-		//-------------------------------------------------------------------
-		// Acquire a cryptographic provider context handle.
-
-		if (!CryptImportKey(m_hCryptProv, (const BYTE *) privateKey, pklen, 0, 0, &hKey))
-		{
-			throw logic_error(string("Error in importing the PrivateKey ") + to_string(GetLastError()));
-		}
-
-		//-------------------------------------------------------------------
-		// Create the hash object.
-
-		if (CryptCreateHash(
-			m_hCryptProv,
-			CALG_SHA1,
-			0,
-			0,
-			&hHash))
-		{
-			printf("Hash object created. \n");
-		}
-		else
-		{
-			CryptDestroyKey(hKey);
-			throw logic_error(string("Error during CryptCreateHash."));
-		}
-		//-------------------------------------------------------------------
-		// Compute the cryptographic hash of the buffer.
-
-		if (CryptHashData(hHash,pbBuffer,dwBufferLen,	0))
-		{
-#ifdef _DEBUG
-			printf("Length of data to be hashed: %d \n", dwBufferLen);
-			printHash(&hHash);
-#endif 
-		}
-		else
-		{
-			throw logic_error(string("Error during CryptHashData."));
-		}
-		//-------------------------------------------------------------------
-		// Determine the size of the signature and allocate memory.
-
-		dwSigLen = 0;
-		if (CryptSignHash(
-			hHash,
-			AT_SIGNATURE,
-			NULL,
-			0,
-			NULL,
-			&dwSigLen))
-		{
-			printf("Signature length %d found.\n", dwSigLen);
-		}
-		else
-		{
-			throw logic_error(string("Error during CryptSignHash."));
-		}
-		//-------------------------------------------------------------------
-		// Allocate memory for the signature buffer.
-
-		if (pbSignature = (BYTE *)malloc(dwSigLen))
-		{
-			printf("Memory allocated for the signature.\n");
-		}
-		else
-		{
-			throw logic_error(string("Out of memory."));
-		}
-		//-------------------------------------------------------------------
-		// Sign the hash object.
-
-		if (CryptSignHash(
-			hHash,
-			AT_SIGNATURE,
-			NULL,
-			0,
-			pbSignature,
-			&dwSigLen))
-		{
-			printf("pbSignature is the signature length. %d\n", dwSigLen);
-		}
-		else
-		{
-			throw logic_error(string("Error during CryptSignHash."));
-		}
-		//-------------------------------------------------------------------
-		// Destroy the hash object.
-
-		
-		CryptDestroyHash(hHash);
+	if (CryptCreateHash(m_hCryptProv, CALG_SHA1, 0, 0, &hHash)) {
+		printf("Hash object created. \n");
+	} else {
 		CryptDestroyKey(hKey);
+		throw logic_error(string("Error during CryptCreateHash."));
+	}
+	//-------------------------------------------------------------------
+	// Compute the cryptographic hash of the buffer.
 
-		CryptBinaryToString(pbSignature,dwSigLen,
+	if (CryptHashData(hHash, pbBuffer, dwBufferLen, 0)) {
+#ifdef _DEBUG
+		printf("Length of data to be hashed: %d \n", dwBufferLen);
+		printHash(&hHash);
+#endif 
+	} else {
+		throw logic_error(string("Error during CryptHashData."));
+	}
+	//-------------------------------------------------------------------
+	// Determine the size of the signature and allocate memory.
+
+	dwSigLen = 0;
+	if (CryptSignHash(hHash, AT_SIGNATURE, NULL, 0, NULL, &dwSigLen)) {
+		printf("Signature length %d found.\n", dwSigLen);
+	} else {
+		throw logic_error(string("Error during CryptSignHash."));
+	}
+	//-------------------------------------------------------------------
+	// Allocate memory for the signature buffer.
+
+	if (pbSignature = (BYTE *) malloc(dwSigLen)) {
+		printf("Memory allocated for the signature.\n");
+	} else {
+		throw logic_error(string("Out of memory."));
+	}
+	//-------------------------------------------------------------------
+	// Sign the hash object.
+
+	if (CryptSignHash(hHash, AT_SIGNATURE,
+	NULL, 0, pbSignature, &dwSigLen)) {
+		printf("pbSignature is the signature length. %d\n", dwSigLen);
+	} else {
+		throw logic_error(string("Error during CryptSignHash."));
+	}
+	//-------------------------------------------------------------------
+	// Destroy the hash object.
+
+	CryptDestroyHash(hHash);
+	CryptDestroyKey(hKey);
+
+	CryptBinaryToString(pbSignature, dwSigLen,
 			CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &strLen);
-		vector<char> buffer(strLen);
-		CryptBinaryToString(pbSignature, dwSigLen,
+	vector<char> buffer(strLen);
+	CryptBinaryToString(pbSignature, dwSigLen,
 			CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, &buffer[0], &strLen);
 
-		//-------------------------------------------------------------------
-		// In the second phase, the hash signature is verified.
-		// This would most often be done by a different user in a
-		// separate program. The hash, signature, and the PUBLICKEYBLOB
-		// would be read from a file, an email message, 
-		// or some other source.
+	//-------------------------------------------------------------------
+	// In the second phase, the hash signature is verified.
+	// This would most often be done by a different user in a
+	// separate program. The hash, signature, and the PUBLICKEYBLOB
+	// would be read from a file, an email message,
+	// or some other source.
 
-		// Here, the original pbBuffer, pbSignature, szDescription. 
-		// pbKeyBlob, and their lengths are used.
+	// Here, the original pbBuffer, pbSignature, szDescription.
+	// pbKeyBlob, and their lengths are used.
 
-		// The contents of the pbBuffer must be the same data 
-		// that was originally signed.
+	// The contents of the pbBuffer must be the same data
+	// that was originally signed.
 
-		//-------------------------------------------------------------------
-		// Get the public key of the user who created the digital signature 
-		// and import it into the CSP by using CryptImportKey. This returns
-		// a handle to the public key in hPubKey.
+	//-------------------------------------------------------------------
+	// Get the public key of the user who created the digital signature
+	// and import it into the CSP by using CryptImportKey. This returns
+	// a handle to the public key in hPubKey.
 
-		/*if (CryptImportKey(
-		hProv,
-		pbKeyBlob,
-		dwBlobLen,
-		0,
-		0,
-		&hPubKey))
-		{
-		printf("The key has been imported.\n");
-		}
-		else
-		{
-		MyHandleError("Public key import failed.");
-		}
-		//-------------------------------------------------------------------
-		// Create a new hash object.
+	/*if (CryptImportKey(
+	 hProv,
+	 pbKeyBlob,
+	 dwBlobLen,
+	 0,
+	 0,
+	 &hPubKey))
+	 {
+	 printf("The key has been imported.\n");
+	 }
+	 else
+	 {
+	 MyHandleError("Public key import failed.");
+	 }
+	 //-------------------------------------------------------------------
+	 // Create a new hash object.
 
-		if (CryptCreateHash(
-		hProv,
-		CALG_MD5,
-		0,
-		0,
-		&hHash))
-		{
-		printf("The hash object has been recreated. \n");
-		}
-		else
-		{
-		MyHandleError("Error during CryptCreateHash.");
-		}
-		//-------------------------------------------------------------------
-		// Compute the cryptographic hash of the buffer.
+	 if (CryptCreateHash(
+	 hProv,
+	 CALG_MD5,
+	 0,
+	 0,
+	 &hHash))
+	 {
+	 printf("The hash object has been recreated. \n");
+	 }
+	 else
+	 {
+	 MyHandleError("Error during CryptCreateHash.");
+	 }
+	 //-------------------------------------------------------------------
+	 // Compute the cryptographic hash of the buffer.
 
-		if (CryptHashData(
-		hHash,
-		pbBuffer,
-		dwBufferLen,
-		0))
-		{
-		printf("The new hash has been created.\n");
-		}
-		else
-		{
-		MyHandleError("Error during CryptHashData.");
-		}
-		//-------------------------------------------------------------------
-		// Validate the digital signature.
+	 if (CryptHashData(
+	 hHash,
+	 pbBuffer,
+	 dwBufferLen,
+	 0))
+	 {
+	 printf("The new hash has been created.\n");
+	 }
+	 else
+	 {
+	 MyHandleError("Error during CryptHashData.");
+	 }
+	 //-------------------------------------------------------------------
+	 // Validate the digital signature.
 
-		if (CryptVerifySignature(
-		hHash,
-		pbSignature,
-		dwSigLen,
-		hPubKey,
-		NULL,
-		0))
-		{
-		printf("The signature has been verified.\n");
-		}
-		else
-		{
-		printf("Signature not validated!\n");
-		}
-		//-------------------------------------------------------------------
-		// Free memory to be used to store signature.
+	 if (CryptVerifySignature(
+	 hHash,
+	 pbSignature,
+	 dwSigLen,
+	 hPubKey,
+	 NULL,
+	 0))
+	 {
+	 printf("The signature has been verified.\n");
+	 }
+	 else
+	 {
+	 printf("Signature not validated!\n");
+	 }
+	 //-------------------------------------------------------------------
+	 // Free memory to be used to store signature.
 
 
 
-		//-------------------------------------------------------------------
-		// Destroy the hash object.
+	 //-------------------------------------------------------------------
+	 // Destroy the hash object.
 
 
 
-		//-------------------------------------------------------------------
-		// Release the provider handle.
+	 //-------------------------------------------------------------------
+	 // Release the provider handle.
 
-		/*if (hProv)
-			CryptReleaseContext(hProv, 0);*/
-		if (pbSignature)
-			free(pbSignature);
-		return string(&buffer[0]);
+	 /*if (hProv)
+	 CryptReleaseContext(hProv, 0);*/
+	if (pbSignature) {
+		free(pbSignature);
 	}
+	return string(&buffer[0]);
+}
 } /* namespace license */

--
Gitblit v1.9.1