This commit is contained in:
2023-12-07 14:51:36 +01:00
parent 31c23daf5e
commit f92b2c708f
40 changed files with 3305 additions and 54 deletions

View File

@@ -3,6 +3,7 @@
#include "utils.h"
#include <filesystem>
#define FILEBUFFER 300
#define TWO_HOURSE_SECONDS 7200
@@ -11,10 +12,10 @@
/// @param argv parametry pro generování licence
/// 1-cid, 2-csd, 3-stanice 4-rozvadec 5-typ licence
/// @return
int main(int argc, char *argv[])
int main5(int argc, char *argv[])
{
map<string, string> arguments = getArguments(argc, argv);
unordered_map<string, string> arguments = getArguments(argc, argv);
PlcLicence plcWriteLicence = PlcLicence(arguments["-cid"], arguments["-csd"], arguments["-outputType"], arguments["-configFileName"]);
if (plcWriteLicence.CreateLicence() == false)
@@ -22,16 +23,7 @@ int main(int argc, char *argv[])
cerr << "Licence creation failed";
}
/* READ LICENCE CODE
// arguments: -cid, -csd, -licenceFi leName, -licenceType=EOV_OSV, -licenceVersion
PlcLicence plcLicence = PlcLicence();
if (plcLicence.ReadLicence(argumentsString["-licenceFileName"], argumentsString["-licenceType"], argumentsString["-licenceVersion"], argumentsString["-cid"], argumentsString["-csd"]) == false)
{
cout << "Reading error: " << plcLicence.operationErrors << endl;
}
*/
return EXIT_SUCCESS;
}

800
src/LicenceELC11.cpp Normal file
View File

@@ -0,0 +1,800 @@
#include <cstring>
#include <fstream>
#include <filesystem>
#include "licenceELC11.h"
#include "utils.h"
#include "pugixml.hpp"
#define CID_LENGTH 32
#define CSD_LENGTH 32
const std::string cEzLic_p78ou3_sdinfofilepath = "/sys/block/mmcblk0/device/";
const std::string cEzLic_p78ou3_licencfilepath_f21 = "/mnt/mmc/ez_sys/licence/";
const std::string cEzLic_p78ou3_licencfilepath_f17 = "/home/admin/ez/licence/";
const string cEzLic_p78ou3_licencfilepath_f10 = "/root/ez_sys/licence/";
const WORD maxDataToFile = 10000; // velikost datoveho bufferu pro ulozeni dat licence
const BYTE licMaxCount = 100;
const DWORD cEzLic_p78ou3_CheckLicNumber_ERR = 0xFFFFFFFF; // 16#FFFFFFFF; // chybna identifikace licence
const DWORD cEzLic_p78ou3_CheckLicNumber_EOV1 = 3781234965; // cislo pro overeni licence EOV, OSV verze 1
const BYTE cEzLic_p78ou3_CheckLicNumberId_ERR = 0; // id licence pro neidentifikovanou licenci
const BYTE cEzLic_p78ou3_CheckLicNumberId_EOV1 = 1; // id licence pro EOV, OSV verze 1
const BYTE cEzLic_p78ou3_MaxCheckLicNumberId = cEzLic_p78ou3_CheckLicNumberId_EOV1; // pocet identifikatoru licenci
const DWORD cEzLic_p78ou3_CheckLicNumber[] = {cEzLic_p78ou3_CheckLicNumber_ERR, cEzLic_p78ou3_CheckLicNumber_EOV1};
const WORD cEzLic_p78ou3_LicPrefixType_ELC1 = 1; // prefix typ1 = pouze zasifrovani dat
const WORD cEzLic_p78ou3_HeaderType_10 = 10; // hlavicka kriptovane casti verze 1.0
const WORD cEzLic_p78ou3_DataType_10 = 10; // data licence verze 1.0
const WORD cEzLic_p78ou3_SubType_10_10 = 0x0A0A; // subtype - verze hlavicky + verze data -> cEzLic_p78ou3_HeaderType_XX * 256 + cEzLic_p78ou3_DataType_XX
// ID aplikace
const WORD cEzLic_p78ou3_IDType_DDTS = 1; // aplikace DDTS
const WORD cEzLic_p78ou3_IDType_EOVOSV = 2; // aplikace EOV-OSV
const WORD cEzLic_p78ou3_IDType_DRT = 3; // aplikace DRT
// std::string cEzLic_p78ou3_IDTypeStrData11[] = {"neznamo", "DDTS", "EOV-OSV", "DRT"};
const BYTE cnibblescount11 = 32;
std::string cSDMonthStr11[] = {"-", "I.", "II.", "III.", "IV.", "V.", "VI.", "VII.", "VIII.", "IX.", "X.", "XI.", "XII.", "-", "-", "-"};
BYTE cHexNibble_to_No11[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const string eoseovLicenceType = "EOV_OSV";
// enum LicenceType { EovOsv = 1 };
LicenceELC11::LicenceELC11()
{
}
LicenceELC11::LicenceELC11(LicenceIdentification &licIdentification)
{
lIdentification = licIdentification;
}
LicenceELC11::LicenceELC11(string cisArg, string csdArg, string binaryType, string dataFileName)
{
for (int i = 0; i < cisArg.length(); i++)
this->cid[i] = cisArg[i];
for (int i = 0; i < csdArg.length(); i++)
this->csd[i] = csdArg[i];
this->stationName = "";
this->distributor = "";
this->licType = 2;
processConfigFile(dataFileName);
if (binaryType == "base64")
this->binaryGeneration = BinaryGenerationType::Base64Cout;
else
this->binaryGeneration = BinaryGenerationType::File;
}
/// @brief process config file
/// @param dataFileName
void LicenceELC11::processConfigFile(string &dataFileName)
{
string fullFile = getCompletePath(dataFileName);
const int fileNameLength = fullFile.length();
char fileName[fileNameLength] = {};
getCharsFromString(fullFile, fileName, fileNameLength);
pugi::xml_document doc;
#ifdef WINDOWS
pugi::xml_parse_result result = doc.load_file("licData.xml");
#else
pugi::xml_parse_result result = doc.load_file(fileName);
#endif
if (result)
{
const char *dataRootName = doc.child("data") ? "data" : "licence"; // kompatibilita s verzí, která měla ještě root "data"
this->stationName = doc.child(dataRootName).child("station").child_value();
this->distributor = doc.child(dataRootName).child("distributor").child_value();
this->dataLicenceType = doc.child(dataRootName).child("licenceType").child_value();
this->dataLicenceVersion = doc.child(dataRootName).child("licenceType").attribute("version").value();
this->dataGenerationType = this->dataLicenceVersion;
this->dataCryptoVersion = this->dataLicenceVersion;
}
else
{
std::cerr << "Unable to open the config file." << std::endl;
}
}
/// @brief reads data from CID a CSD
void LicenceELC11::getSDData()
{
for (int i = 0; i < CID_LENGTH; i++)
this->sdData.CID_nibble[i] = (BYTE)cid[i];
for (int i = 0; i < cnibblescount / 2; i++)
{
this->sdData.CID[i] = cHexNibble_to_No11[this->sdData.CID_nibble[2 * i]] << 4 | cHexNibble_to_No11[this->sdData.CID_nibble[2 * i + 1]];
}
this->sdData.manufacturerID = this->sdData.CID[0];
this->sdData.oemID[0] = this->sdData.CID[1];
this->sdData.oemID[1] = this->sdData.CID[2];
this->sdData.name[0] = this->sdData.CID[3];
this->sdData.name[1] = this->sdData.CID[4];
this->sdData.name[2] = this->sdData.CID[5];
this->sdData.name[3] = this->sdData.CID[6];
this->sdData.name[4] = this->sdData.CID[7];
this->sdData.productRevision_hw = cHexNibble_to_No11[this->sdData.CID[16]];
this->sdData.productRevision_sw = cHexNibble_to_No11[this->sdData.CID[17]];
if (this->sdData.productRevision_sw < 10)
this->sdData.productRevision = (float)this->sdData.productRevision_hw + ((float)this->sdData.productRevision_sw * 0.1);
else
this->sdData.productRevision = (float)this->sdData.productRevision_hw + ((float)this->sdData.productRevision_sw * 0.01);
this->sdData.serialNumber = this->sdData.CID[9] << 24 | this->sdData.CID[10] << 16 | this->sdData.CID[11] << 8 | this->sdData.CID[12];
this->sdData.manufacturerDate_year = cHexNibble_to_No11[this->sdData.CID_nibble[27]] * 10 + cHexNibble_to_No11[this->sdData.CID_nibble[28]] + 2000;
this->sdData.manufacturerDate_month = cHexNibble_to_No11[this->sdData.CID_nibble[29]];
string date = cSDMonthStr11[this->sdData.manufacturerDate_month] + std::to_string(this->sdData.manufacturerDate_year);
for (int i = 0; i < date.length(); i++)
this->sdData.manufacturerDate[i] = date[i];
// CSD
for (int i = 0; i < CSD_LENGTH; i++)
this->sdData.CSD_nibble[i] = (BYTE)csd[i];
for (int i = 0; i < cnibblescount / 2; i++)
{
//
this->sdData.CSD[i] = cHexNibble_to_No11[this->sdData.CSD_nibble[2 * i]] << 4 | cHexNibble_to_No11[this->sdData.CSD_nibble[2 * i + 1]];
}
if (this->sdData.CSD_nibble[0] == 0x34)
{
this->sdData.cardSize = this->sdData.CSD[7] << 16 | this->sdData.CSD[8] << 8 | this->sdData.CSD[9];
this->sdData.cardGSize = (this->sdData.cardSize + 1) / 2048;
if (this->sdData.cardSize > 17200) // TODO result.cardSize
{
}
}
BYTE sdCrc = 0;
for (int i = 0; i <= 14; i++)
{
BYTE sdChar = this->sdData.CID[i];
for (int j = 0; j <= 7; j++)
{
sdCrc = sdCrc << 1;
if ((sdChar ^ sdCrc) & 0x80)
sdCrc = sdCrc ^ 0x09;
sdChar = sdChar << 1;
}
sdCrc = sdCrc & 0x7F;
}
this->sdData.CRCOK = ((sdCrc << 1) | 1) == this->sdData.CID[15];
}
/// @brief inits keys and vectors for encrypting
void LicenceELC11::initCrypto()
{
if (this->licType == cEzLic_p78ou3_IDType_EOVOSV)
{
this->cryptData.aesInitVector[0] = this->sdData.CID[10];
this->cryptData.aesInitVector[1] = this->sdData.CID[12];
this->cryptData.aesInitVector[2] = this->sdData.CID[11];
this->cryptData.aesInitVector[3] = this->sdData.CID[9];
this->cryptData.aesInitVector[4] = this->sdData.CID_nibble[22] - 15;
this->cryptData.aesInitVector[5] = this->sdData.CID_nibble[24] - 15;
this->cryptData.aesInitVector[6] = this->sdData.CID_nibble[25] - 15;
this->cryptData.aesInitVector[7] = this->sdData.CID_nibble[21] - 15;
memcpy(&this->cryptData.aesInitVector[8], &this->cryptData.aesInitVector[0], 8);
this->cryptData.aesKey[0] = this->sdData.CID[12];
this->cryptData.aesKey[1] = this->sdData.CID_nibble[23] - 15;
this->cryptData.aesKey[2] = this->sdData.CID_nibble[25] - 15;
this->cryptData.aesKey[3] = this->sdData.CID[11];
this->cryptData.aesKey[4] = this->sdData.CID[9];
this->cryptData.aesKey[5] = this->sdData.CID_nibble[21] - 15;
this->cryptData.aesKey[6] = 97 + this->sdData.CID[9] % 25;
this->cryptData.aesKey[7] = this->sdData.CID_nibble[22] - 15;
memcpy(&this->cryptData.aesKey[8], &this->cryptData.aesKey[0], 8);
memcpy(&this->cryptData.aesKey[16], &this->cryptData.aesKey[6], 8);
memcpy(&this->cryptData.aesKey[24], &this->cryptData.aesKey[12], 8);
}
}
string LicenceELC11::getLicenceName()
{
string result = "";
char prefixChar = 97;
int licType = (int)lIdentification.licLicenceType;
int lVersion = lIdentification.licenceVersion;
int licIndex = lIdentification.licenceIndex;
// natvrdo, stará ELC
result = "ezlic_eovosv" + to_string(licIndex) + "_";
result += prefixChar + (this->sdCard.cardData.CID[12] % 25);
result += prefixChar + (this->sdCard.cardData.CID[10] % 25);
result += prefixChar + (this->sdCard.cardData.CID_nibble[22] % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[23] * 2) % 25);
result += prefixChar + (this->sdCard.cardData.CID_nibble[24] % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[25] * 3) % 25);
result += prefixChar + (this->sdCard.cardData.CID[9] % 25);
result += prefixChar + (this->sdCard.cardData.CID[11] % 25);
result += prefixChar + (this->sdCard.cardData.CID[2] % 25);
result += prefixChar + (this->sdCard.cardData.CID[1] % 25);
result += prefixChar + (this->sdCard.cardData.CID[3] % 25);
result += ".lic";
return result;
}
/// @brief get proper licencename
/// @param licPostfix
/// @return
string LicenceELC11::getLicenceName(BYTE licPostfix)
{
string result = "";
char prefixChar = 97;
if (licPostfix > 9) // chyba
{
}
if (licType == PlcLicenceType::LicenceOther)
{
result = "ezlic_";
result += prefixChar + (this->sdData.CID[12] % 25);
result += prefixChar + (this->sdData.CID[10] % 25);
result += prefixChar + (this->sdData.CID_nibble[22] % 25);
result += prefixChar + ((this->sdData.CID_nibble[23] * 2) % 25);
result += prefixChar + (this->sdData.CID_nibble[24] % 25);
result += prefixChar + ((this->sdData.CID_nibble[25] * 3) % 25);
result += prefixChar + (this->sdData.CID[9] % 25);
result += prefixChar + (this->sdData.CID[11] % 25);
result += prefixChar + (this->sdData.CID[2] % 25);
result += prefixChar + (this->sdData.CID[1] % 25);
result += prefixChar + (this->sdData.CID[3] % 25);
result += ".lic";
}
else
{
result = "ezlic_eovosv" + to_string(licPostfix) + "_";
result += prefixChar + (this->sdData.CID[12] % 25);
result += prefixChar + (this->sdData.CID[10] % 25);
result += prefixChar + (this->sdData.CID_nibble[22] % 25);
result += prefixChar + ((this->sdData.CID_nibble[23] * 2) % 25);
result += prefixChar + (this->sdData.CID_nibble[24] % 25);
result += prefixChar + ((this->sdData.CID_nibble[25] * 3) % 25);
result += prefixChar + (this->sdData.CID[9] % 25);
result += prefixChar + (this->sdData.CID[11] % 25);
result += prefixChar + (this->sdData.CID[2] % 25);
result += prefixChar + (this->sdData.CID[1] % 25);
result += prefixChar + (this->sdData.CID[3] % 25);
result += ".lic";
}
return result;
}
bool LicenceELC11::createLicence()
{
if (this->dataLicenceType == eoseovLicenceType)
{
return createEosEovLicence();
}
else
{
return false;
}
}
bool LicenceELC11::createEosEovLicence()
{
getSDData();
initCrypto();
// promenne pro praci se soubory a adresari
LicenceDataMainELC dataMainToFileELC1; //: tEz_LicenceDataMainELC1; hlavicka urcena pro zapis do souboru - typ ELC1
LicenceData dataToFile; // tEz_LicenceData_10_10; // data urcena pro sifrovani a zapis do soubotu - verze => hlavicka: 1.0, data: 1.0
// pomocne promenne
BYTE dataWriteToFile[maxDataToFile]; // OF BYTE; data zapisovana do souboru
string licencePostfix; //: STRING; pomocna promenna pro kontrolu postfixu
string mainLicDescription; //: STRING(79); globalni pojmenovani licence v nesifrovane casti licence
UINT freeDataSize; //: UINT; velikost volne citelnych dat v souboru licenci
UINT cryptDataSize; //: UINT; velikost volne cryptovanych dat v souboru licenci
UINT fullDataSize; //: UINT; celkova velikost souboru licenci
USINT generation = 2; //: USINT; verze SW pro licence
PlcData plcData;
plcData.licenceName = "Licence";
plcData.licenceType = "1";
plcData.station = stationName;
plcData.distributor = distributor;
LicenceSourceData licSourceData;
if (plcData.licenceType == "EOV" || plcData.licenceType == to_string((int)PlcLicenceType::LicenceEov))
{
licSourceData.licType = 0x1AA2; // 6818 ... proč ?
licSourceData.licPostfix = 0;
getCharsFromString(plcData.station, licSourceData.licDescription1);
getCharsFromString(plcData.station, dataToFile.header.licDescription1);
getCharsFromString(plcData.distributor, licSourceData.licDescription2);
getCharsFromString(plcData.distributor, dataToFile.header.licDescription2);
}
LicenceIdent licIdent;
licIdent.licPrefixType = licSourceData.licType >> 12;
licIdent.licHeaderType = licSourceData.licType >> 8 & 0x000F;
licIdent.licDataType = licSourceData.licType >> 4 & 0x000F;
licIdent.licSubType = licIdent.licHeaderType << 8 | licIdent.licHeaderType;
licIdent.licIDType = licSourceData.licType & 0x000F;
if (licSourceData.licPostfix > 9)
licSourceData.licPostfix = 0;
licencePostfix = to_string(licSourceData.licPostfix);
string licenseFileName = getLicenceName(0);
licSourceData.licPostfixIdent = right(licencePostfix, 1);
int sizeOfData = sizeof(dataToFile);
if (licIdent.licHeaderType == cEzLic_p78ou3_HeaderType_10)
{
if (licIdent.licDataType == cEzLic_p78ou3_DataType_10)
{
dataToFile.id.version = 10;
dataToFile.id.cardSize = this->sdData.cardSize;
switch (licIdent.licIDType)
{
case cEzLic_p78ou3_IDType_DDTS:
mainLicDescription = "ddts ";
break;
case cEzLic_p78ou3_IDType_EOVOSV:
mainLicDescription = "eov, osv ";
break;
default:
mainLicDescription = "neznama app ";
}
mainLicDescription += licSourceData.licPostfixIdent;
mainLicDescription += " => ";
dataToFile.header.licVersion = 10;
dataToFile.header.licType = licIdent.licIDType;
dataToFile.header.licDate = getLicDate(); // 1692230400; //getLicDate(); //1692144000;// getLicDate();
mainLicDescription += dataToFile.header.licDescription1;
mainLicDescription += " [";
mainLicDescription += dataToFile.header.licDescription2;
mainLicDescription += "]";
if (licIdent.licIDType == cEzLic_p78ou3_IDType_EOVOSV)
{
if (generation == 1) // stará verze
{
dataToFile.header.licCount = 1;
dataToFile.items[0].licCount = 65535;
dataToFile.items[0].protoId = cEzLic_p78ou3_CheckLicNumberId_EOV1;
dataToFile.items[0].data1 = cEzLic_p78ou3_CheckLicNumber_EOV1;
}
else
{
dataToFile.header.licCount = 1;
dataToFile.items[1].licCount = 999;//65535;
dataToFile.items[1].protoId = cEzLic_p78ou3_CheckLicNumberId_EOV1;
dataToFile.items[1].data1 = cEzLic_p78ou3_CheckLicNumber_EOV1;
}
}
unsigned char encrypted[10000] = {};
const int s = sizeof(dataToFile);
unsigned char byteArray[s] = {};
memcpy(byteArray, &dataToFile, sizeof(dataToFile));
dataToFile.crc = calculateCRC16(byteArray, s - sizeof(dataToFile.crc)); // 47535 | 884:38382
memcpy(byteArray, &dataToFile, sizeof(dataToFile));
int finalEncryptedLength = encrypt(byteArray, sizeof(dataToFile), this->cryptData.aesKey, this->cryptData.aesInitVector, encrypted);
if (licIdent.licPrefixType == cEzLic_p78ou3_LicPrefixType_ELC1) // typ1 = pouze zasifrovani dat
{
freeDataSize = sizeof(dataMainToFileELC1); // melo by byt 92
if (1) // EzLic_p78ou3_CryptoData.aesRetVal > 0 crypto
{
dataMainToFileELC1.prefix = 0x31434C45;
getCharsFromString(mainLicDescription, dataMainToFileELC1.licHeader.description);
dataMainToFileELC1.licHeader.sizeData = finalEncryptedLength; // sizeof(dataToFile); // 884;
dataMainToFileELC1.licHeader.licType = licIdent.licIDType;
dataMainToFileELC1.licHeader.licSubType = licIdent.licHeaderType << 8 | licIdent.licDataType;
}
}
const int dataMainLength = sizeof(dataMainToFileELC1);
const int dataToFileLength = sizeof(dataToFile);
const int dataEncryptedLength = finalEncryptedLength;
const int totalLength = dataMainLength + dataToFileLength;
const int totalEncryptedLength = dataMainLength + finalEncryptedLength;
unsigned char bdataMainToFileELC1[dataMainLength] = {};
memcpy(bdataMainToFileELC1, &dataMainToFileELC1, dataMainLength);
unsigned char bdataToFile[dataToFileLength] = {};
memcpy(bdataToFile, &dataToFile, dataToFileLength);
unsigned char totalEncryptedArray[totalEncryptedLength] = {};
for (int i = 0; i < dataMainLength; i++)
totalEncryptedArray[i] = bdataMainToFileELC1[i];
for (int i = 0; i < finalEncryptedLength; i++)
totalEncryptedArray[i + dataMainLength] = encrypted[i];
string fullFile = getCompletePath(licenseFileName);
if (binaryGeneration == BinaryGenerationType::File)
{
#ifdef WINDOWS
char licFileNameToSave[licenseFileName.length()] = {};
getCharsFromString(licenseFileName, licFileNameToSave, licenseFileName.length());
FILE *fileLicence = fopen(licFileNameToSave, "wb");
if (fileLicence)
{
size_t r1 = fwrite(&totalEncryptedArray, sizeof(totalEncryptedArray), 1, fileLicence);
// printf("License binary saved.\n");
fclose(fileLicence);
cout << licenseFileName << endl;
return true;
}
#else
std::ofstream outputFile(fullFile);
if (outputFile.is_open())
{
outputFile.write(reinterpret_cast<const char *>(totalEncryptedArray), totalEncryptedLength);
outputFile.close();
std::cout << licenseFileName;
}
else
{
std::cerr << "Unable to open licence file." << std::endl;
}
return true;
#endif
}
else
{
int totalFileSize = sizeof(totalEncryptedArray);
// cout << "data:text/plain;base64,";
cout << "data:application/octet-stream;base64,";
char encryptedChars[totalFileSize];
for (int i = 0; i < totalFileSize; i++)
encryptedChars[i] = static_cast<signed char>(totalEncryptedArray[i]);
string strToBase = convertToString(encryptedChars, totalFileSize);
string base64Coded = base64_encode_ai(strToBase);
cout << base64Coded << endl;
return true;
}
}
}
return false;
}
bool LicenceELC11::readEosEovLicence(string dataFileName)
{
BYTE licPostfix = 0;
FILE *licenceFile;
char ch;
long lSize;
size_t result;
const int fileNameLength = dataFileName.length();
char fileNameCh[fileNameLength] = {};
for (int i = 0; i < dataFileName.length(); i++)
fileNameCh[i] = dataFileName[i];
cout << dataFileName << endl;
licenceFile = fopen(fileNameCh, "rb"); // read mode
fseek(licenceFile, 0, SEEK_END); // seek to end of file
const int size = ftell(licenceFile); // get current file pointer
fseek(licenceFile, 0, SEEK_SET);
if (licenceFile == nullptr)
{
perror("Error while opening the file.\n");
operationErrors = "Error while opening the file.\n";
return false;
}
int count = 0;
unsigned char licenceContent[size];
for (int i = 0; i < size; i++)
{
ch = fgetc(licenceFile);
licenceContent[i] = ch;
count++;
}
fclose(licenceFile);
// this->cid = cid;
// this->csd = csd;
getSDData();
string licFileName = getLicenceName(licPostfix);
LicenceDataMainELC licenceHeader;
LicenceIdent licIdent;
LicenceData licEncryptedData;
memset(&licenceHeader, 0, sizeof(LicenceDataMainELC));
memcpy(&licenceHeader, licenceContent, sizeof(LicenceDataMainELC));
const int sizeOfEncryptedData = size - sizeof(LicenceDataMainELC);
unsigned char encryptedData[sizeOfEncryptedData] = {};
for (int i = 0; i < sizeOfEncryptedData; i++)
encryptedData[i] = licenceContent[i + sizeof(LicenceDataMainELC)];
// original jsou testy na velikost přečteného file, zatím TODO
BYTE prefixType = (int)licenceContent[3] - 0x30;
if (prefixType == PrefixType::ELC1)
{
if (licenceHeader.licHeader.sizeData > 0)
{
licIdent.licIDType = licenceHeader.licHeader.licType;
licIdent.licSubType = licenceHeader.licHeader.licSubType;
if (licenceHeader.licHeader.licSubType == cEzLic_p78ou3_SubType_10_10) // zatim natvrdo
{
initCrypto();
// CryptData cryptData = initCrypto(sdData, licIdent.licIDType);
unsigned char decrypted[2000] = {};
int decrypted_len = decrypt(encryptedData, sizeof(encryptedData), cryptData.aesKey, cryptData.aesInitVector, decrypted);
if (sizeof(licEncryptedData) != decrypted_len)
{
operationErrors = "License size mismatch";
return false;
}
else
{
memset(&licEncryptedData, 0, sizeof(licEncryptedData));
memcpy(&licEncryptedData, decrypted, sizeof(licEncryptedData));
if (licEncryptedData.id.version == cEzLic_p78ou3_HeaderType_10 && licEncryptedData.header.licVersion == cEzLic_p78ou3_HeaderType_10)
{
if (licEncryptedData.header.licType == cEzLic_p78ou3_IDType_EOVOSV)
{
if (licEncryptedData.id.cardSize != sdData.cardSize)
{
operationErrors = "Size card mismatch";
return false;
}
if (licEncryptedData.header.licCount > 0)
{
if (licType == PlcLicenceType::LicenceOther)
{
// TODO stará
}
else
{
// maxLic := MIN(EzLlic_5rq4_DataFromFile_10_10.header.licCount, cEzLic_p78ou3_licMaxCount); ?
int maxLic = min(licEncryptedData.header.licCount, licMaxCount);
for (int i = 1; i < maxLic; i++)
{
if (licEncryptedData.items[i].protoId > 0 || licEncryptedData.items[i].licCount > 0 || licEncryptedData.items[i].data1 > 0)
{
// EzLlic_5rq4_CheckData.LicId[EzLlic_5rq4_DataFromFile_10_10.items[licId].protoId] := licId;
}
else
{
operationErrors = "Licence items mismatch";
return false;
}
}
}
}
else
{
operationErrors = "Size card info mismatch";
return false;
}
}
}
else
{
operationErrors = "Licence mismatch";
return false;
}
}
}
}
else
{
operationErrors = "Licence error";
return false;
}
}
else
{
operationErrors = "Licence error";
return false;
}
cout << "Licence readed: " << size << endl
<< ", data: " << licenceHeader.licHeader.description << endl;
return true;
}
bool LicenceELC11::readLicence(LicenceInfoGeneral *licences)
{
sdCard = SDCard(this->cid_cdsPath);
if (sdCard.isLoaded == false)
throw LicenceException((int)51, "Chyba při čtení SD karty, cesta: " + cid_cdsPath);
for (int i = 0; i < sdCard.cidString.length(); i++)
this->cid[i] = sdCard.cidString[i]; // nutné pro původní algoritmus
for (int i = 0; i < sdCard.csdString.length(); i++)
this->csd[i] = sdCard.csdString[i]; // nutné pro původní algoritmus
string licFileName = getLicenceName();
string licFilePath = this->licenceFilePath + licFileName;
BYTE licPostfix = 0;
FILE *licenceFile;
char ch;
long lSize;
size_t result;
const int fileNameLength = licFilePath.length();
char fileNameCh[fileNameLength] = {};
for (int i = 0; i < fileNameLength; i++)
fileNameCh[i] = licFilePath[i];
licenceFile = fopen(fileNameCh, "rb"); // read mode
fseek(licenceFile, 0, SEEK_END); // seek to end of file
const int size = ftell(licenceFile); // get current file pointer
fseek(licenceFile, 0, SEEK_SET);
if (size <= 0)
throw LicenceException((int)Error11::LicenceReadError, "Licence read error: " + licFilePath);
int count = 0;
unsigned char licenceContent[size];
for (int i = 0; i < size; i++)
{
ch = fgetc(licenceFile);
licenceContent[i] = ch;
count++;
}
fclose(licenceFile);
getSDData();
LicenceDataMainELC licenceHeader;
LicenceIdent licIdent;
LicenceData licEncryptedData;
memset(&licenceHeader, 0, sizeof(LicenceDataMainELC));
memcpy(&licenceHeader, licenceContent, sizeof(LicenceDataMainELC));
const int sizeOfEncryptedData = size - sizeof(LicenceDataMainELC);
unsigned char encryptedData[sizeOfEncryptedData] = {};
for (int i = 0; i < sizeOfEncryptedData; i++)
encryptedData[i] = licenceContent[i + sizeof(LicenceDataMainELC)];
BYTE prefixType = (int)licenceContent[3] - 0x30;
if (prefixType == PrefixType::ELC1)
{
if (licenceHeader.licHeader.sizeData > 0)
{
licIdent.licIDType = licenceHeader.licHeader.licType;
licIdent.licSubType = licenceHeader.licHeader.licSubType;
if (licenceHeader.licHeader.licSubType == cEzLic_p78ou3_SubType_10_10) // zatim natvrdo
{
initCrypto();
// CryptData cryptData = initCrypto(sdData, licIdent.licIDType);
unsigned char decrypted[2000] = {};
int decrypted_len = decrypt(encryptedData, sizeof(encryptedData), cryptData.aesKey, cryptData.aesInitVector, decrypted);
#ifdef DEB
cout << "sizeof(licEncryptedData: " << sizeof(licEncryptedData) << endl;
cout << "decrypted_len: " << decrypted_len << endl;
#endif
if (sizeof(licEncryptedData) != decrypted_len)
{
throw LicenceException((int)Error11::LicenceSizeMismatch, "License size mismatch ");
}
else
{
memset(&licEncryptedData, 0, sizeof(licEncryptedData));
memcpy(&licEncryptedData, decrypted, sizeof(licEncryptedData));
if (licEncryptedData.id.version == cEzLic_p78ou3_HeaderType_10 && licEncryptedData.header.licVersion == cEzLic_p78ou3_HeaderType_10)
{
if (licEncryptedData.header.licType == cEzLic_p78ou3_IDType_EOVOSV)
{
if (licEncryptedData.header.licCount > 0)
{
for (int i = 0; i < licMaxCount; i++)
{
licences->licences.insert(pair<int, int>(licEncryptedData.items[i].protoId, licEncryptedData.items[i].licCount));
}
}
else
{
throw LicenceException((int)Error11::LicenceSizeCardMismatch, "Size card info mismatch");
}
}
}
else
{
throw LicenceException((int)Error11::LicenceMismatch, "Licence mismatch");
}
}
}
}
else
{
throw LicenceException((int)Error11::LicenceMismatch, "Licence mismatch");
}
}
else
{
throw LicenceException((int)Error11::LicenceReadError, "Licence error");
}
return true;
}
bool LicenceELC11::readLicence(string dataFileName, string licenceType, string licenceVersion, string cidArg, string csdArg)
{
for (int i = 0; i < cidArg.length(); i++)
this->cid[i] = cidArg[i];
for (int i = 0; i < csdArg.length(); i++)
this->csd[i] = csdArg[i];
this->dataLicenceType = licenceType;
this->dataLicenceVersion = licenceVersion;
if (this->dataLicenceType == eoseovLicenceType)
{
return readEosEovLicence(dataFileName);
}
return true;
}
LicenceELC11::~LicenceELC11() {}

45
src/LicenceELC31.cpp Normal file
View File

@@ -0,0 +1,45 @@
#include "licenceELC31.h"
#include "utils.h"
#include <map>
#include <vector>
LicenceELC31::LicenceELC31()
{
}
LicenceELC31::LicenceELC31(LicData &licData)
{
lData = licData;
processInputConfiguration();
}
LicenceELC31::LicenceELC31(LicenceIdentification &licIdentification)
{
}
bool LicenceELC31::processInputConfiguration()
{
return true;
}
int LicenceELC31::getDataPointsCount(int protocolId)
{
return 0;
}
bool LicenceELC31::getLicenceInfo(int protocolId, void * ptr)
{
return true;
}
void LicenceELC31::createLicence()
{
}
void LicenceELC31::readLicence()
{
}
LicenceELC31::~LicenceELC31() { }

489
src/LicenceGenerator.cpp Normal file
View File

@@ -0,0 +1,489 @@
#include <stdio.h>
#include <filesystem>
#include <cstdlib>
#include <licenceGenerator.h>
#include "utils.h"
#include "pugixml.hpp"
#include <typeinfo>
ELCType licElcType = ELCType::ELC2;
LicenceType licLicenceType;
PlcType licPlcType;
uint8_t licenceVersion = 1; // verze licence, určitě kodování, pojmenování souborů
uint8_t licenceIndex = 0;
uint8_t revision;
uint8_t licCompatibility = 1; // identikator hlavního ELC
LicenceGenerator::LicenceGenerator()
{
}
LicenceGenerator::LicenceGenerator(string uid, string cid, string csd, string dataFileName)
{
try
{
if (dataFileName.empty())
throw std::runtime_error("Missing dataFileName par.");
if (uid.empty() == false)
{
this->licData.uid = uid;
}
else
{
if (cid.empty())
throw std::runtime_error("Missing CID par.");
if (csd.empty())
throw std::runtime_error("Missing CSD par.");
}
}
catch (const std::exception &e)
{
this->argumentsCorrect = false;
std::cerr << "error: " << e.what() << endl;
return;
}
this->configFileName = dataFileName;
this->licData.cid = cid;
this->licData.csd = csd;
this->argumentsCorrect = true;
if (processInputConfiguration() == false)
{
cerr << "Chyba: " << error.message << endl;
}
}
LicenceGenerator::LicenceGenerator(map<string, string> &arguments)
{
}
LicenceGenerator::LicenceGenerator(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility)
{
this->licIdentification.licElcType = (ELCType)elcType;
this->licIdentification.licLicenceType = (LicenceType)licenceType;
this->licIdentification.licenceVersion = licenceVersion;
this->licIdentification.licenceIndex = licenceIndex;
this->licIdentification.licCompatibility = compatibility;
}
/// @brief inicializace generátoru a načtení licenčních bodů
/// @param elcType
/// @param licenceType
/// @param licenceVersion
/// @param licenceIndex
/// @param compatibility
/// @return
bool LicenceGenerator::initread(InitStructure &initStructure)
{
try
{
elcSwitchType = initStructure.elcType * 10 + licCompatibility;
if (init(initStructure))
{
switch (elcSwitchType)
{
case 11:
{ // old eoseov
LicenceELC11 licence = LicenceELC11(this->licIdentification);
licence.readLicence(&this->licenceInfo);
break;
}
case 21:
{
LicenceELC21 licence = LicenceELC21(this->licIdentification);
this->licence21 = &licence;
this->licence21->readLicence(&this->licenceInfo);
break;
}
case 31:
{
LicenceELC31 licence = LicenceELC31(this->licIdentification);
break;
}
}
}
else
return false;
}
catch (const LicenceException &ex)
{
error.code = ex.getErrorCode();
error.message = ex.getErrorMessage();
return false;
}
return true; // TODO testy
}
bool LicenceGenerator::initread(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility)
{
try
{
elcSwitchType = elcType * 10 + licCompatibility;
if (init(elcType, licenceType, licenceVersion, licenceIndex, compatibility))
{
switch (elcSwitchType)
{
case 11:
{ // old eoseov
LicenceELC11 licence = LicenceELC11(this->licIdentification);
licence.readLicence(&this->licenceInfo);
break;
}
case 21:
{
LicenceELC21 licence = LicenceELC21(this->licIdentification);
this->licence21 = &licence;
this->licence21->readLicence(&this->licenceInfo);
break;
}
case 31:
{
LicenceELC31 licence = LicenceELC31(this->licIdentification);
break;
}
}
}
else
return false;
}
catch (const LicenceException &ex)
{
error.code = ex.getErrorCode();
error.message = ex.getErrorMessage();
return false;
}
return true; // TODO testy
}
/// @brief inicicialize generátoro, pouze vstupní kontrola
/// @param elcType
/// @param licenceType
/// @param licenceVersion
/// @param licenceIndex
/// @param compatibility
/// @return
bool LicenceGenerator::init(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility)
{
try
{
if (elcType > 3)
{
error.code = (int)GeneralError::ELCNotImplemented;
error.message = "ELC není implementováno.";
throw LicenceException((int)GeneralError::ELCNotImplemented, error.message);
return false;
}
this->licIdentification.licElcType = (ELCType)elcType;
this->licIdentification.licLicenceType = (LicenceType)licenceType;
this->licIdentification.licenceVersion = licenceVersion;
this->licIdentification.licenceIndex = licenceIndex;
this->licIdentification.licCompatibility = compatibility;
}
catch (const LicenceException &ex)
{
error.code = ex.getErrorCode();
error.message = ex.getErrorMessage();
return false;
}
elcSwitchType = elcType * 10 + licCompatibility;
return true; // TODO testy
}
bool LicenceGenerator::init(InitStructure &initStructure)
{
try
{
if (initStructure.elcType > 3)
{
error.code = (int)GeneralError::ELCNotImplemented;
error.message = "ELC není implementováno.";
throw LicenceException((int)GeneralError::ELCNotImplemented, error.message);
return false;
}
this->licIdentification.licElcType = (ELCType)initStructure.elcType;
this->licIdentification.licLicenceType = (LicenceType)initStructure.licenceType;
this->licIdentification.licenceVersion = licenceVersion;
this->licIdentification.licenceIndex = licenceIndex;
this->licIdentification.licCompatibility = initStructure.compatibility;
}
catch (const LicenceException &ex)
{
error.code = ex.getErrorCode();
error.message = ex.getErrorMessage();
return false;
}
elcSwitchType = initStructure.elcType * 10 + licCompatibility;
return true; // TODO testy
}
int LicenceGenerator::getDataPointsCount(int protocolId)
{
}
bool LicenceGenerator::getLicenceItemInfo(int protocolId, void *returnItemStructure)
{
int result = 0;
// const type_info &ti1 = typeid(LicenceELC21);
try
{
switch (elcSwitchType)
{
case 11:
{ // old eoseov
LicenceItem11 *resultPtr = static_cast<LicenceItem11 *>(returnItemStructure);
resultPtr->protocolId = protocolId; // protocolId;
if (this->licenceInfo.licences.count(protocolId))
resultPtr->dataPointsCount = this->licenceInfo.licences.at(protocolId);
else
resultPtr->dataPointsCount = 0;
// licence21->getLicenceItemInfo(protocolId, returnItemStructure); stará verze, nová má k dispozici polozky z readLicence
break;
}
case 21:
{
LicenceItem21 *resultPtr = static_cast<LicenceItem21 *>(returnItemStructure);
resultPtr->protocolId = protocolId; // protocolId;
if (this->licenceInfo.licences.count(protocolId))
resultPtr->dataPointsCount = this->licenceInfo.licences.at(protocolId);
else
resultPtr->dataPointsCount = 0;
// licence21->getLicenceItemInfo(protocolId, returnItemStructure); stará verze, nová má k dispozici polozky z readLicence
break;
}
case 31:
{
LicenceELC31 licence = LicenceELC31(this->licIdentification);
break;
}
default:
{
error.code = -1;
error.message = "Nepodařilo se identifikovat licenci";
return false;
}
}
}
catch (const LicenceException &ex)
{
error.code = ex.getErrorCode();
error.message = ex.getErrorMessage();
return false;
}
return true;
}
bool LicenceGenerator::getLicenceInfo(int protocolId, void *returnStructure)
{
int result = 0;
const type_info &ti1 = typeid(LicenceELC21);
// const type_info& ti1 = typeid(returnStructure);
// cout << "TTTYP: " << ti1.name() << endl;
switch (elcSwitchType)
{
case 11:
{ // old eoseov
break;
}
case 21:
{
LicenceELC21 licence = LicenceELC21(this->licIdentification);
try
{
licence.readLicence(&this->licenceInfo);
return licence.getLicenceInfo(protocolId, returnStructure);
}
catch (const LicenceException &ex)
{
error.code = ex.getErrorCode();
error.message = ex.getErrorMessage();
return false;
}
break;
}
case 31:
{
LicenceELC31 licence = LicenceELC31(this->licIdentification);
try
{
licence.readLicence();
return licence.getLicenceInfo(protocolId, returnStructure);
}
catch (const LicenceException &ex)
{
error.code = ex.getErrorCode();
error.message = ex.getErrorMessage();
return false;
}
break;
}
}
error.code = -1;
error.message = "Nepodařilo se identifikovat licenci";
return false;
}
bool LicenceGenerator::processInputConfiguration()
{
string fullFile = getCompletePath(this->configFileName);
const int fileNameLength = fullFile.length();
char fileName[fileNameLength] = {};
getCharsFromString(fullFile, fileName, fileNameLength);
#ifdef WINDOWS
pugi::xml_parse_result result = doc.load_file("licData.xml");
#else
pugi::xml_parse_result result = doc.load_file(fileName);
#endif
if (result)
{
const char *dataRootName = doc.child("data") ? "data" : "licence"; // kompatibilita s verzí, která měla ještě root "data"
Mapping mapping;
if (atoi(&doc.child(dataRootName).attribute("xmlVersion").value()[0]) != XML_VERSION)
{
error.code = -1;
error.message = "Invalid XML VERSION";
return false;
}
this->licData.doc = &doc;
string licType = doc.child(dataRootName).child("licenceType").child_value();
if (!licType.empty())
{
this->licIdentification.licLicenceType = mapping.licMapTypes[licType]; // LicenceType::EOS_EOV;
}
else
{
cerr << endl
<< " ERROR MISSING licenceType " << endl;
return false;
}
this->licIdentification.licenceVersion = atoi(&doc.child(dataRootName).child("licenceType").attribute("licenceVersion").value()[0]);
this->licIdentification.revision = doc.child(dataRootName).attribute("revision").value()[0];
this->licIdentification.licenceIndex = atoi(&doc.child(dataRootName).child("licenceType").attribute("licenceIndex").value()[0]);
this->licIdentification.licElcType = (ELCType)atoi(&doc.child(dataRootName).attribute("elc").value()[0]);
licElcType = (ELCType)atoi(&doc.child(dataRootName).attribute("elc").value()[0]);
licCompatibility = atoi(&doc.child(dataRootName).attribute("compatibility").value()[0]);
this->licIdentification.licCompatibility = atoi(&doc.child(dataRootName).attribute("compatibility").value()[0]);
string plcType = doc.child(dataRootName).child("plcType").child_value();
if (!plcType.empty())
{
this->licIdentification.licPlcType = mapping.licMapPlcType[plcType];
}
}
else
{
std::cerr << "Unable to open the config file." << std::endl;
}
return true;
}
void LicenceGenerator::createLicenceFile()
{
switch (licElcType)
{
case ELCType::ELC1:
createLicenceELC1();
break;
case ELCType::ELC2:
createLicenceELC2();
break;
case ELCType::ELC3:
createLicenceELC3();
break;
}
}
void LicenceGenerator::readLicenceFile()
{
switch (this->licIdentification.licElcType)
{
case ELCType::ELC1:
readLicenceELC1();
break;
case ELCType::ELC2:
readLicenceELC2();
break;
case ELCType::ELC3:
readLicenceELC3();
break;
}
}
void LicenceGenerator::createLicenceELC1() // přejmenvat na ELC1
{
LicenceELC11 plcWriteLicence = LicenceELC11(this->licData.cid, this->licData.csd, "file", this->configFileName);
plcWriteLicence.createLicence();
}
void LicenceGenerator::createLicenceELC2()
{
switch (licCompatibility)
{
case 1:
LicenceELC21 licence = LicenceELC21(this->licData);
licence.createLicence();
break;
}
}
void LicenceGenerator::createLicenceELC3()
{
switch (licCompatibility)
{
case 1:
LicenceELC31 licence = LicenceELC31(this->licData);
licence.createLicence();
break;
}
}
void LicenceGenerator::readLicenceELC1()
{
cout << "reading ELC1" << endl;
}
void LicenceGenerator::readLicenceELC2()
{
LicenceELC21 licence = LicenceELC21(this->licIdentification);
}
void LicenceGenerator::readLicenceELC3()
{
cout << "reading ELC3" << endl;
}
LicenceGenerator::~LicenceGenerator()
{
}

69
src/NewGeneration.cpp Normal file
View File

@@ -0,0 +1,69 @@
#include <stdio.h>
#include "utils.h"
#include "licenceGenerator.h"
#include "licenceCommon.h"
/// @brief hlavní funkce
/// @param argc
/// @param argv parametry pro generování licence
/// @return
int main(int argc, char *argv[])
{
// cout << "test" << endl;
// unordered_map<string, string> arguments = getArguments(argc, argv);
// LicenceGenerator generatorOld = LicenceGenerator(arguments["-uid"], arguments["-cid"], arguments["-csd"], arguments["-configFileName"]);
// generatorOld.createLicenceFile();
// return 0;
//cout << "Reading Test" << endl;
LicenceGenerator licenceGenerator = LicenceGenerator();
InitStructure initStructure;
initStructure.elcType = 2;
initStructure.licenceType = (int)LicenceType::EOS_EOV;
initStructure.licenceVersion = 1;
initStructure.licenceIndex = 0;
initStructure.compatibility = 1;
initStructure.licenceFilePath = "";
// if (licenceGenerator.init(initStructure))
// {
// LicenceInfo21 info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
// if (licenceGenerator.getLicenceInfo(888, &info))
// {
// std::cout << "Počet licenčních bodů pro 888: " << info.reqDataPointsCount << std::endl;
// if (info.licences.count(888) > 0) cout << "počet z vectoru pro 888: " << info.licences.at(888) << endl;
// cout << "všechny licenční body: " << endl;
// for (const auto& pair : info.licences) { std::cout << "<" << pair.first << ", " << pair.second << ">" << endl;
// }
// }
// else
// cerr << "Došlo k chybě: " << licenceGenerator.error.message;
// }
// else
// {
// cerr << "Došlo k chybě: " << licenceGenerator.error.message;
// }
if (licenceGenerator.initread(initStructure))
{
LicenceItem21 info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
if (licenceGenerator.getLicenceItemInfo(777, &info))
{
std::cout << "Počet licenčních bodů pro " << info.protocolId << ": " << info.dataPointsCount << std::endl;
//for (const auto& pair : info.licences) { std::cout << "<" << pair.first << ", " << pair.second << ">" << endl;
}
else cerr << "Došlo k chybě: " << licenceGenerator.error.message;
}
else
{
cerr << "Došlo k chybě: " << licenceGenerator.error.message;
}
system("pause");
return EXIT_SUCCESS;
}

View File

@@ -52,6 +52,7 @@ BYTE cHexNibble_to_No[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
std::string cEzLic_p78ou3_CipherAES = "aes-256-cbc"; // konfigurace kriptovaciho algoritmu
const string eoseovLicenceType = "EOV_OSV";
//enum LicenceType { EovOsv = 1 };
PlcLicence::PlcLicence()
{
@@ -86,6 +87,9 @@ void PlcLicence::processConfigFile(string &dataFileName)
char fileName[fileNameLength] = {};
getCharsFromString(fullFile, fileName, fileNameLength);
std::map<std::string, LicenceType> licTypes;
licTypes["EOV_OSV"] = LicenceType::LicenceEov;
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(fileName);
if (result)
@@ -599,8 +603,7 @@ bool PlcLicence::ReadEosEovLicence(string dataFileName)
return false;
}
cout << "Licence readed: " << size << endl
<< ", data: " << licenceHeader.licHeader.description << endl;
cout << "Licence readed: " << size << endl << ", data: " << licenceHeader.licHeader.description << endl;
return true;
}

116
src/SDCard.cpp Normal file
View File

@@ -0,0 +1,116 @@
#include "utils.h"
#include "SDCard.h"
#include <map>
#include <vector>
#include <fstream>
SDCard::SDCard()
{
}
SDCard::SDCard(const string cds_cid_Path)
{
this->filePath = cds_cid_Path;
getCIDFromFile();
getCSDFromFile();
this->isLoaded = SDCard::readSDCard();
}
SDCard::SDCard(string cid, string csd)
{
for (int i = 0; i < cid.length(); i++)
this->cid[i] = cid[i];
for (int i = 0; i < csd.length(); i++)
this->csd[i] = csd[i];
this->isLoaded = SDCard::readSDCard();
}
bool SDCard::readSDCard()
{
BYTE cHexNibbleToNo[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < CID_LENGTH; i++)
this->cardData.CID_nibble[i] = (BYTE)cid[i];
for (int i = 0; i < cnibblescount / 2; i++)
{
this->cardData.CID[i] = cHexNibbleToNo[this->cardData.CID_nibble[2 * i]] << 4 | cHexNibbleToNo[this->cardData.CID_nibble[2 * i + 1]];
}
this->cardData.manufacturerID = this->cardData.CID[0];
this->cardData.oemID[0] = this->cardData.CID[1];
this->cardData.oemID[1] = this->cardData.CID[2];
this->cardData.name[0] = this->cardData.CID[3];
this->cardData.name[1] = this->cardData.CID[4];
this->cardData.name[2] = this->cardData.CID[5];
this->cardData.name[3] = this->cardData.CID[6];
this->cardData.name[4] = this->cardData.CID[7];
this->cardData.productRevision_hw = cHexNibbleToNo[this->cardData.CID[16]];
this->cardData.productRevision_sw = cHexNibbleToNo[this->cardData.CID[17]];
if (this->cardData.productRevision_sw < 10)
this->cardData.productRevision = (float)this->cardData.productRevision_hw + ((float)this->cardData.productRevision_sw * 0.1);
else
this->cardData.productRevision = (float)this->cardData.productRevision_hw + ((float)this->cardData.productRevision_sw * 0.01);
this->cardData.serialNumber = this->cardData.CID[9] << 24 | this->cardData.CID[10] << 16 | this->cardData.CID[11] << 8 | this->cardData.CID[12];
// this->cardData.manufacturerDate_year = cHexNibbleToNo[this->cardData.CID_nibble[27]] * 10 + cHexNibbleToNo[this->cardData.CID_nibble[28]] + 2000;
// this->cardData.manufacturerDate_month = cHexNibbleToNo[this->cardData.CID_nibble[29]];
// string date = cSDMonthStr[this->cardData.manufacturerDate_month] + std::to_string(this->cardData.manufacturerDate_year);
// for (int i = 0; i < date.length(); i++) this->cardData.manufacturerDate[i] = date[i];
// CSD
for (int i = 0; i < CSD_LENGTH; i++)
this->cardData.CSD_nibble[i] = (BYTE)csd[i];
for (int i = 0; i < cnibblescount / 2; i++)
{
this->cardData.CSD[i] = cHexNibbleToNo[this->cardData.CSD_nibble[2 * i]] << 4 | cHexNibbleToNo[this->cardData.CSD_nibble[2 * i + 1]];
}
if (this->cardData.CSD_nibble[0] == 0x34)
{
this->cardData.cardSize = this->cardData.CSD[7] << 16 | this->cardData.CSD[8] << 8 | this->cardData.CSD[9];
this->cardData.cardGSize = (this->cardData.cardSize + 1) / 2048;
}
return true;
}
bool SDCard::getCIDFromFile()
{
// string cid = "9f544930303030300000000b47015423";
cidString = readFileToString(this->filePath + "cid", 32);
if (cidString.empty()) return false;
for (int i = 0; i < cidString.length(); i++) this->cid[i] = cidString[i];
return true;
}
bool SDCard::getCSDFromFile()
{
// string cid = "9f544930303030300000000b47015423";
csdString = readFileToString(this->filePath + "csd", 32);
if (csdString.empty()) return false;
for (int i = 0; i < csdString.length(); i++) this->csd[i] = csdString[i];
return true;
}

5
src/cid Normal file
View File

@@ -0,0 +1,5 @@
9f5449534443495461457815de0164a9
6   . x4 <20><><EFBFBD>  .. nt$6 &<26> manfid 6 <20><><EFBFBD>
 cid "6 <10> fwrev 6 Jm<4A>  csd ,6 gEd$
subsystem 46 <20><><EFBFBD>%
driver (6 <20><><EFBFBD>-  ocr -6 <20><><EFBFBD>? power *6 <>4L  type 6 <20>1M  date #6 <20>rTP hwrev )6 n<>yR  dsr '6 <20>` serial 6 NN<4E>m erase_size <20>6 <20>6<EFBFBD>m block 6 <20><><EFBFBD>n uevent 6 <18><>o  ssr 6 <1E>q  scr &6 &<26><>y oemid !6 <20><><EFBFBD>y ( preferred_erase_size %6 <20><><EFBFBD>  name

2
src/csd Normal file
View File

@@ -0,0 +1,2 @@
400e00325b5900003a0d7f800a40008d

674
src/licenceELC21.cpp Normal file
View File

@@ -0,0 +1,674 @@
#include "licenceELC21.h"
#include "utils.h"
#include "SDCard.h"
#include <unordered_map>
#include <vector>
#include <limits>
#include <fstream>
LicenceELC21::LicenceELC21()
{
}
LicenceELC21::LicenceELC21(LicenceIdentification &licIdentification, LicData &licData)
{
lIdentification = licIdentification;
lData = licData;
}
LicenceELC21::LicenceELC21(LicenceIdentification &licIdentification)
{
lIdentification = licIdentification;
}
LicenceELC21::LicenceELC21(LicData &licData)
{
lData = licData;
processInputConfiguration();
}
bool LicenceELC21::createLicence()
{
getLicenceItems();
getHeader();
sdCard = SDCard(lData.cid, lData.csd);
if (sdCard.isLoaded == false)
cerr << "SD card read error." << endl;
this->licBody.licenceIdentHeader.cardSize = sdCard.cardData.cardSize;
this->licBody.licenceIdentHeader.serialNumber = sdCard.cardData.serialNumber;
this->licBody.licenceIdentHeader.licItemCount = this->licBody.privateContent.dataItems.size();
this->licBody.licenceIdentHeader.publicHeaderLength = this->licBody.publicHeader.length();
vector<unsigned char> publicContent;
publicContent.reserve(1000);
vector<unsigned char> privateContent;
privateContent.reserve(1000);
vector<unsigned char> privateContentEncrypted;
privateContentEncrypted.reserve(1000);
publicContent.push_back(this->licBody.licId.licIdent[0]);
publicContent.push_back(this->licBody.licId.licIdent[1]);
publicContent.push_back(this->licBody.licId.licIdent[2]);
publicContent.push_back(((char)48 + (int)this->lIdentification.licElcType));
publicContent.push_back(this->licBody.licId.licIdent[4]);
publicContent.push_back(this->licBody.licenceIdentHeader.licenceType);
publicContent.push_back(this->licBody.licenceIdentHeader.licenceTypeVersion);
publicContent.push_back(this->licBody.licenceIdentHeader.licenceIndex);
publicContent.push_back(this->licBody.licenceIdentHeader.compatibilityVersion);
publicContent.push_back(this->licBody.privateContent.dataItems.size());
publicContent.push_back(this->licBody.licenceIdentHeader.publicHeaderLength & 0xFF);
publicContent.push_back((this->licBody.licenceIdentHeader.publicHeaderLength >> 8) & 0xFF);
publicContent.push_back(this->licBody.licenceIdentHeader.cardSize & 0xFF);
publicContent.push_back((this->licBody.licenceIdentHeader.cardSize >> 8) & 0xFF);
publicContent.push_back(this->licBody.licenceIdentHeader.serialNumber & 0xFF);
publicContent.push_back((this->licBody.licenceIdentHeader.serialNumber >> 8) & 0xFF);
publicContent.push_back((this->licBody.licenceIdentHeader.serialNumber >> 16) & 0xFF);
publicContent.push_back((this->licBody.licenceIdentHeader.serialNumber >> 24) & 0xFF);
#ifdef DEB
cout << "publicHeaderLength: " << this->licBody.licenceIdentHeader.publicHeaderLength << endl;
cout << "cardSize: " << this->licBody.licenceIdentHeader.cardSize << endl;
cout << "serialNumber: " << this->licBody.licenceIdentHeader.serialNumber << endl;
cout << "item count: " << this->licBody.privateContent.dataItems.size() << endl;
#endif
appendStringToVector(this->licBody.publicHeader, publicContent);
uint16_t crcPublic = calculateCRC16(publicContent);
#ifdef DEB
cout << "CRC pubblic: " << crcPublic << endl;
#endif
publicContent.push_back(crcPublic & 0xFF);
publicContent.push_back((crcPublic >> 8) & 0xFF);
privateContent.push_back(this->licBody.licenceIdentHeader.licenceType);
privateContent.push_back(this->licBody.licenceIdentHeader.licenceTypeVersion);
privateContent.push_back(this->licBody.licenceIdentHeader.licenceIndex);
privateContent.push_back(this->licBody.licenceIdentHeader.compatibilityVersion);
privateContent.push_back(this->licBody.privateContent.dataItems.size());
privateContent.push_back(this->licBody.licenceIdentHeader.publicHeaderLength & 0xFF);
privateContent.push_back((this->licBody.licenceIdentHeader.publicHeaderLength >> 8) & 0xFF);
privateContent.push_back(this->licBody.licenceIdentHeader.cardSize & 0xFF);
privateContent.push_back((this->licBody.licenceIdentHeader.cardSize >> 8) & 0xFF);
privateContent.push_back(this->licBody.licenceIdentHeader.serialNumber & 0xFF);
privateContent.push_back((this->licBody.licenceIdentHeader.serialNumber >> 8) & 0xFF);
privateContent.push_back((this->licBody.licenceIdentHeader.serialNumber >> 16) & 0xFF);
privateContent.push_back((this->licBody.licenceIdentHeader.serialNumber >> 24) & 0xFF);
for (licDataItem dataItem : this->licBody.privateContent.dataItems)
{
privateContent.push_back(dataItem.protoId & 0xFF);
privateContent.push_back((dataItem.protoId >> 8) & 0xFF);
privateContent.push_back(dataItem.licCount & 0xFF);
privateContent.push_back((dataItem.licCount >> 8) & 0xFF);
for (int i = 0; i < sizeof(dataItem.dummy); i++)
privateContent.push_back(i);
}
vector<unsigned char> completeVector = joinVectors(publicContent, privateContent);
licBody.privateContent.crc = calculateCRC16(completeVector);
uint16_t crcComplete = calculateCRC16(completeVector);
privateContent.push_back(crcComplete & 0xFF);
privateContent.push_back((crcComplete >> 8) & 0xFF);
privateContentEncrypted = cryptPrivateContent(privateContent);
#ifdef DEB
cout << endl
<< hex << "test original: " << privateContent.size() << endl;
for (auto x : privateContent)
cout << (int)x << "-";
cout << endl
<< "test encrypt: " << privateContentEncrypted.size() << endl;
for (auto x : privateContentEncrypted)
cout << (int)x << "-";
vector<unsigned char> privateContentDecrypted;
privateContentDecrypted = decryptPrivateContent(privateContentEncrypted);
cout << endl
<< "test decrypt: " << privateContentDecrypted.size() << endl;
for (auto x : privateContentDecrypted)
cout << (int)x << "-";
#endif
// return;
string licfileName = getLicenceName();
std::ofstream outputFile(licfileName, std::ios::out | std::ios::binary);
// Check if the file is open
if (!outputFile.is_open())
{
std::cerr << "Error opening file: " << licfileName << std::endl;
return false;
}
std::copy(publicContent.cbegin(), publicContent.cend(), std::ostream_iterator<unsigned char>(outputFile));
std::copy(privateContentEncrypted.cbegin(), privateContentEncrypted.cend(), std::ostream_iterator<unsigned char>(outputFile));
outputFile.close();
cout << licfileName;
return true;
}
bool LicenceELC21::readLicence(LicenceInfoGeneral * licences)
{
try
{
// sdCard = SDCard("9f544930303030300000000b47015423", "400e00325b5900003a0d7f800a40008d");
sdCard = SDCard(this->cid_cdsPath);
if (sdCard.isLoaded == false)
throw LicenceException((int)Error21::SDCardReadError, "Chyba při čtení SD karty, cesta: " + cid_cdsPath);
string licFileName = getLicenceName();
string licFilePath = this->licenceFilePath+licFileName;
// Create an unsigned char vector to store the file data
vector<char> content;
if (readFile(licFilePath, content) == false)
{
throw LicenceException((int)GeneralError::FileOpenError, "Chyba otevření souboru licence.");
}
this->licBody.licId.licIdent[0] = content[0];
this->licBody.licId.licIdent[1] = content[1];
this->licBody.licId.licIdent[2] = content[2];
this->licBody.licId.licIdent[3] = content[3];
this->licBody.licId.licIdent[4] = content[4];
this->licBody.licenceIdentHeader.licenceType = content[5];
this->licBody.licenceIdentHeader.licenceTypeVersion = content[6];
this->licBody.licenceIdentHeader.licenceIndex = content[7];
this->licBody.licenceIdentHeader.compatibilityVersion = content[8];
this->licBody.licenceIdentHeader.licItemCount = content[9];
this->licBody.licenceIdentHeader.publicHeaderLength = bytesToWord(content[10], content[11]);
this->licBody.licenceIdentHeader.cardSize = bytesToWord(content[12], content[13]);
this->licBody.licenceIdentHeader.serialNumber = bytesToDword(content[14], content[15], content[16], content[17]);
uint16_t crcPublic = bytesToWord(content[18 + licBody.licenceIdentHeader.publicHeaderLength], content[19 + licBody.licenceIdentHeader.publicHeaderLength]);
#ifdef DEB
cout << "licenceType: " << to_string(licBody.licenceIdentHeader.licenceType) << endl;
cout << "licenceTypeVersion: " << to_string(licBody.licenceIdentHeader.licenceTypeVersion) << endl;
cout << "licenceIndex: " << to_string(licBody.licenceIdentHeader.licenceIndex) << endl;
cout << "compatibilityVersion: " << to_string(licBody.licenceIdentHeader.compatibilityVersion) << endl;
cout << "licItemCount: " << to_string(licBody.licenceIdentHeader.licItemCount) << endl;
cout << "headerLength: " << to_string(licBody.licenceIdentHeader.publicHeaderLength) << endl;
cout << "card: " << to_string(licBody.licenceIdentHeader.cardSize) << endl;
cout << "serial: " << to_string(licBody.licenceIdentHeader.serialNumber) << endl;
cout << "crcPublic: " << to_string(crcPublic) << endl;
#endif
int elcVersion = (int)licBody.licId.licIdent[3] - 48;
if (elcVersion != (int)this->lIdentification.licElcType)
{
throw LicenceException((int)GeneralError::ELCMismatch, "Nesouhlasí ELC.");
}
vector<unsigned char> encryptedPart(content.begin() + licBody.licenceIdentHeader.publicHeaderLength + 20, content.begin() + content.size());
#ifdef DEB
cout << " encrypted part: " << hex << encryptedPart.size() << endl;
for (auto x : encryptedPart)
{
cout << (int)x << "-";
}
#endif
vector<unsigned char> privateContentDecrypted;
privateContentDecrypted = decryptPrivateContent(encryptedPart);
#ifdef DEB
cout << dec << endl
<< " decrypted part: " << privateContentDecrypted.size() << endl;
for (auto x : privateContentDecrypted)
{
cout << dec << (int)x << "-";
}
#endif
LicenceBody licBodyDecrypted;
licBodyDecrypted.licenceIdentHeader.licenceType = privateContentDecrypted[0];
licBodyDecrypted.licenceIdentHeader.licenceTypeVersion = privateContentDecrypted[1];
licBodyDecrypted.licenceIdentHeader.licenceIndex = privateContentDecrypted[2];
licBodyDecrypted.licenceIdentHeader.compatibilityVersion = privateContentDecrypted[3];
licBodyDecrypted.licenceIdentHeader.licItemCount = privateContentDecrypted[4];
licBodyDecrypted.licenceIdentHeader.publicHeaderLength = bytesToWord(privateContentDecrypted[5], privateContentDecrypted[6]);
licBodyDecrypted.licenceIdentHeader.cardSize = bytesToWord(privateContentDecrypted[7], privateContentDecrypted[8]);
licBodyDecrypted.licenceIdentHeader.serialNumber = bytesToDword(privateContentDecrypted[9], privateContentDecrypted[10], privateContentDecrypted[11], privateContentDecrypted[12]);
//TODO testy na CRC
if (licBodyDecrypted.licenceIdentHeader.licItemCount != this->licBody.licenceIdentHeader.licItemCount)
{
throw LicenceException((int)Error21::ItemsCountMismatch, map21Errors.at(Error21::ItemsCountMismatch));
}
int index = 13;
for (int i = 0; i < this->licBody.licenceIdentHeader.licItemCount; i++)
{
licDataItem item;
item.protoId = bytesToWord(privateContentDecrypted[index], privateContentDecrypted[index + 1]);
item.licCount = bytesToWord(privateContentDecrypted[index + 2], privateContentDecrypted[index + 3]);
index = index + sizeof(licDataItem);
this->licBody.privateContent.dataItems.push_back(item);
this->licenceInfo.licences.insert(pair<int, int>(item.protoId, item.licCount));
licences->licences.insert(pair<int, int>(item.protoId, item.licCount));
}
}
catch (const LicenceException &ex)
{
errorMessage.code = ex.getErrorCode();
errorMessage.message = ex.getErrorMessage();
return false;
}
return true;
}
string LicenceELC21::getVersion(int middleVersion)
{
string result = "";
result.append(to_string(generatorVersion));
result.append(".");
result.append(to_string(middleVersion));
result.append(".");
string tempLicenceCount = "3"; // TODO
result.append(tempLicenceCount);
return result;
}
bool LicenceELC21::processInputConfiguration()
{
const char *dataRootName = "licence";
Mapping mapping;
string licType = lData.doc->child(dataRootName).child("licenceType").child_value();
if (!licType.empty())
{
this->lIdentification.licLicenceType = mapping.licMapTypes[licType]; // LicenceType::EOS_EOV;
this->lIdentification.licTypeName = licType;
}
else
{
cerr << endl
<< " ERROR MISSING licenceType " << endl;
return false;
}
this->lIdentification.licenceVersion = atoi(&lData.doc->child(dataRootName).child("licenceType").attribute("licenceVersion").value()[0]);
this->lIdentification.revision = lData.doc->child(dataRootName).attribute("revision").value()[0];
this->lIdentification.licenceIndex = atoi(&lData.doc->child(dataRootName).child("licenceType").attribute("licenceIndex").value()[0]);
this->lIdentification.licElcType = (ELCType)atoi(&lData.doc->child(dataRootName).attribute("elc").value()[0]);
this->lIdentification.licCompatibility = atoi(&lData.doc->child(dataRootName).attribute("compatibility").value()[0]);
string plcType = lData.doc->child(dataRootName).child("plcType").child_value();
if (!plcType.empty())
{
this->lIdentification.licPlcType = mapping.licMapPlcType[plcType];
}
this->lData.station = &lData.doc->child(dataRootName).child("station").child_value()[0];
this->lData.distributor = &lData.doc->child(dataRootName).child("distributor").child_value()[0];
this->lData.projectDescription = &lData.doc->child(dataRootName).child("project").child_value()[0];
licBody.licenceIdentHeader.cardSize = 0;
licBody.licenceIdentHeader.compatibilityVersion = this->lIdentification.licCompatibility;
licBody.licenceIdentHeader.licenceIndex = this->lIdentification.licenceIndex;
licBody.licenceIdentHeader.licenceType = this->lIdentification.licenceVersion;
licBody.licenceIdentHeader.licenceTypeVersion = this->lIdentification.licenceVersion;
licBody.licenceIdentHeader.serialNumber = 0;
return true;
}
void LicenceELC21::getLicenceItems()
{
int nodeIndex = 0;
int itemIndex = 0;
for (pugi::xml_node licItemNode : lData.doc->child("licence").child("items"))
{
licDataItem item;
#ifdef DEB
cout << "protoId: " << licItemNode.child("protoId").child_value() << endl;
cout << "datapoints: " << licItemNode.child("dataPointsCount").child_value() << endl;
#endif
item.protoId = atoi(licItemNode.child("protoId").child_value());
item.licCount = atoi(licItemNode.child("dataPointsCount").child_value());
this->licBody.privateContent.dataItems.push_back(item);
nodeIndex = 0;
itemIndex++;
for (pugi::xml_node child : licItemNode.children())
{
nodeIndex++;
if (nodeIndex == 1)
{
licBody.publicHeader.append("\"name\":\"");
licBody.publicHeader.append(child.child_value());
licBody.publicHeader.append("\",");
continue;
}
if (nodeIndex == 3)
{
licBody.publicHeader.append("\"dataPointsCount\":\"");
licBody.publicHeader.append(child.child_value());
licBody.publicHeader.append("\"");
}
}
if (itemIndex != lIdentification.licItemsCount)
{
licBody.publicHeader.append("},");
}
else
{
licBody.publicHeader.append("}");
}
}
}
void LicenceELC21::getHeader()
{
PublicHeader publicHeader;
publicHeader.version = getVersion(7);
publicHeader.projectDescription = lData.projectDescription;
publicHeader.date = getDate();
publicHeader.licenceType = lIdentification.licTypeName;
publicHeader.licenceType += to_string(lIdentification.licenceIndex);
licBody.publicHeader = "";
licBody.publicHeader.append("{\"version\":");
licBody.publicHeader.append(publicHeader.version);
licBody.publicHeader.append("\",");
// \"1.2.3\",");
licBody.publicHeader.append("\"project\":\"");
licBody.publicHeader.append(publicHeader.projectDescription);
licBody.publicHeader.append("\",");
licBody.publicHeader.append("\"date\":\"");
licBody.publicHeader.append(publicHeader.date);
licBody.publicHeader.append("\",");
licBody.publicHeader.append("\"note\":\"poznámka\",");
licBody.publicHeader.append("\"licenceType\":\"");
licBody.publicHeader.append(publicHeader.licenceType);
licBody.publicHeader.append("\",");
licBody.publicHeader.append("\"items\":[");
for (pugi::xml_node tool : lData.doc->child("licence").child("items"))
{
lIdentification.licItemsCount++;
}
int nodeIndex = 0;
int itemIndex = 0;
for (pugi::xml_node licItemNode : lData.doc->child("licence").child("items"))
{
licBody.publicHeader.append("{");
nodeIndex = 0;
itemIndex++;
for (pugi::xml_node child : licItemNode.children())
{
nodeIndex++;
if (nodeIndex == 1)
{
licBody.publicHeader.append("\"name\":\"");
licBody.publicHeader.append(child.child_value());
licBody.publicHeader.append("\",");
continue;
}
if (nodeIndex == 3)
{
licBody.publicHeader.append("\"dataPointsCount\":\"");
licBody.publicHeader.append(child.child_value());
licBody.publicHeader.append("\"");
}
}
if (itemIndex != lIdentification.licItemsCount)
{
licBody.publicHeader.append("},");
}
else
{
licBody.publicHeader.append("}");
}
}
licBody.publicHeader.append("]");
licBody.publicHeader.append("}");
}
vector<unsigned char> LicenceELC21::cryptPrivateContent(const std::vector<unsigned char> &content)
{
BYTE initVector[15] = {0};
BYTE aesKey[32] = {0};
LicenceELC21::initVector(initVector, aesKey);
unsigned char encrypted[10000] = {};
const unsigned char *plainTextArray = content.data();
int finalEncryptedLength = encrypt(plainTextArray, content.size(), aesKey, initVector, encrypted);
std::size_t charArraySize = sizeof(encrypted) / sizeof(unsigned char);
std::vector<unsigned char> result(encrypted, encrypted + finalEncryptedLength);
return result;
}
vector<unsigned char> LicenceELC21::decryptPrivateContent(const std::vector<unsigned char> &content)
{
BYTE initVector[15] = {0};
BYTE aesKey[32] = {0};
LicenceELC21::initVector(initVector, aesKey);
const unsigned char *encryptedData = content.data();
unsigned char decrypted[10000] = {};
int decrypted_len = decrypt(encryptedData, content.size(), aesKey, initVector, decrypted);
std::size_t charArraySize = sizeof(decrypted) / sizeof(unsigned char);
std::vector<unsigned char> result(decrypted, decrypted + decrypted_len);
return result;
}
void LicenceELC21::initVector(BYTE (&iVector)[], BYTE (&key)[])
{
struct Vector15
{
int vec[15];
};
Vector15 vec1 = {this->sdCard.cardData.CID[10],
this->sdCard.cardData.CID[12],
this->sdCard.cardData.CID[11],
this->sdCard.cardData.CID[9],
this->sdCard.cardData.CID_nibble[22] - 15,
this->sdCard.cardData.CID_nibble[24] - 15,
this->sdCard.cardData.CID_nibble[25] - 15,
this->sdCard.cardData.CID_nibble[21] - 15,
9, 10, 11, 12, 13, 14, 15};
Vector15 vec2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; //TODO přidat smysluplnější indexy
Vector15 vec3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
std::unordered_map<int, Vector15> vectors;
vectors.insert(std::pair<int, Vector15>(1, vec1));
vectors.insert(std::pair<int, Vector15>(2, vec2));
vectors.insert(std::pair<int, Vector15>(3, vec3));
struct Key32
{
int key[32];
};
Key32 key1 = {this->sdCard.cardData.CID[12],
this->sdCard.cardData.CID[23] - 15,
this->sdCard.cardData.CID[25] - 15,
this->sdCard.cardData.CID[11],
this->sdCard.cardData.CID[9],
this->sdCard.cardData.CID_nibble[21],
this->sdCard.cardData.CID[9] % 25,
this->sdCard.cardData.CID_nibble[22] - 15,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Key32 key2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
Key32 key3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
std::unordered_map<int, Key32> keys;
keys.insert(std::pair<int, Key32>(1, key1));
keys.insert(std::pair<int, Key32>(2, key2));
keys.insert(std::pair<int, Key32>(3, key3));
int lVersion = lIdentification.licenceVersion;
iVector[0] = vectors.at(lVersion).vec[0];
iVector[1] = vectors.at(lVersion).vec[1];
iVector[2] = vectors.at(lVersion).vec[2];
iVector[3] = vectors.at(lVersion).vec[3];
iVector[4] = vectors.at(lVersion).vec[4];
iVector[5] = vectors.at(lVersion).vec[5];
iVector[6] = vectors.at(lVersion).vec[6];
iVector[7] = vectors.at(lVersion).vec[7];
memcpy(&iVector[8], &iVector[0], 8);
key[0] = keys.at(lVersion).key[0];
key[1] = keys.at(lVersion).key[1];
key[2] = keys.at(lVersion).key[2];
key[3] = keys.at(lVersion).key[3];
key[4] = keys.at(lVersion).key[4];
key[5] = keys.at(lVersion).key[5];
key[6] = keys.at(lVersion).key[6];
key[7] = keys.at(lVersion).key[7];
memcpy(&key[8], &key[0], 8);
memcpy(&key[16], &key[6], 8);
memcpy(&key[24], &key[12], 8);
}
/// @brief get proper licencename
/// @param licPostfix
/// @return
string LicenceELC21::getLicenceName()
{
// note - bude stačit pouze měnit indexy nebo bude potřeba udělat novej rozcestnik? nyni necháno na indexech
string result = "";
char prefixChar = 97;
int licType = (int)lIdentification.licLicenceType;
int lVersion = lIdentification.licenceVersion;
unordered_map<int, string> baseString;
baseString.insert(std::pair<int, string>((int)LicenceType::EOS_EOV, "ezlic_eovosv"));
baseString.insert(std::pair<int, string>((int)LicenceType::DDTS, "ezlic_ddts"));
baseString.insert(std::pair<int, string>((int)LicenceType::DRT, "ezlic_drt"));
struct Index
{
int index[11];
};
std::unordered_map<int, Index> indexes;
Index indexes1 = {7, 16, 20, 23, 18, 4, 9, 11, 6, 9, 13};
Index indexes2 = {12, 10, 22, 23, 24, 25, 9, 11, 2, 1, 3}; // puvodní indexy
Index indexes3 = {7, 16, 20, 23, 18, 4, 9, 11, 6, 9, 13};
indexes.insert(std::pair<int, Index>(1, indexes1));
indexes.insert(std::pair<int, Index>(2, indexes2));
indexes.insert(std::pair<int, Index>(3, indexes3));
result = baseString.at(licType) + to_string(lIdentification.licenceIndex) + "_";
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[0]] + (lIdentification.licenceIndex * 11)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[1]] + (lIdentification.licenceIndex * 39)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[2]] + (lIdentification.licenceIndex * 1)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[3]] * 2) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[4]] + (lIdentification.licenceIndex * 5)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[5]] * 3) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[6]] + (lIdentification.licenceIndex * 52)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[7]] + (lIdentification.licenceIndex * 34)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[8]] + (lIdentification.licenceIndex * 21)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[9]] + (lIdentification.licenceIndex * 47)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[10]] + (lIdentification.licenceIndex * 7)) % 25);
result += ".lic";
return result;
}
int LicenceELC21::getDataPointsCount(int protocolId)
{
if (this->readLicence(nullptr) == false)
{
}
for (auto item : this->licBody.privateContent.dataItems)
{
if (item.protoId == protocolId)
return item.licCount;
}
return 0;
}
bool LicenceELC21::getLicenceItemInfo(int protocolId, void *returnItemStructure)
{
if (returnItemStructure != nullptr)
{
LicenceItem21 *resultPtr = static_cast<LicenceItem21 *>(returnItemStructure);
resultPtr->protocolId = protocolId; // protocolId;
if (this->licenceInfo.licences.count(protocolId)) resultPtr->dataPointsCount=this->licenceInfo.licences.at(protocolId);
else resultPtr->dataPointsCount = 0;
}
else
{
errorMessage.code = 1;
errorMessage.message = "Error: Null pointer!";
return false;
}
return true;
}
bool LicenceELC21::getLicenceInfo(int protocolId, void *returnStructure)
{
if (returnStructure != nullptr)
{
LicenceInfo21 *resultPtr = static_cast<LicenceInfo21 *>(returnStructure);
for (auto item : this->licBody.privateContent.dataItems)
{
resultPtr->licences.insert(pair<int, int>(item.protoId, item.licCount));
if (item.protoId == protocolId) resultPtr->reqDataPointsCount = item.licCount;
}
}
else
{
errorMessage.code = 1;
errorMessage.message = "Error: Null pointer!";
return false;
}
return true;
}
LicenceELC21::~LicenceELC21() {}

View File

@@ -1,4 +1,4 @@
#include <iostream>
#include <stdint.h>
#include <vector>
#include <wchar.h>
@@ -11,7 +11,8 @@
#include <iterator>
#include <sstream>
#include <codecvt>
#include <map>
#include <unordered_map>
#include <format>
// #include <openssl/evp.h>
// #include <openssl/aes.h>
@@ -75,7 +76,10 @@ void getCharsFromString1(string source, char *charArray)
void getCharsFromString(string &source, char *charArray, int length)
{
memset(charArray, 0, length);
for (int i = 0; i < length; i++) { charArray[i] = source[i]; }
for (int i = 0; i < length; i++)
{
charArray[i] = source[i];
}
}
void getCharsFromString(string source, char *charArray)
@@ -399,6 +403,14 @@ DATE getLicDate()
return dateOnly;
}
string getDate()
{
auto r = std::chrono::system_clock::now();
auto rp = std::chrono::system_clock::to_time_t(r);
std::string h(ctime(&rp)); // converting to c++ string
return h;
}
std::vector<unsigned char> aes256_cbc_encrypt(const std::vector<unsigned char> &plaintext, const std::vector<unsigned char> &key, const std::vector<unsigned char> &iv)
{
std::vector<unsigned char> ciphertext;
@@ -430,7 +442,7 @@ void handleErrors(void)
abort();
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext)
{
EVP_CIPHER_CTX *ctx;
@@ -475,7 +487,7 @@ int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
@@ -725,10 +737,10 @@ std::string base64_encode_ai(const std::string &input)
return encoded;
}
map<string, string> getArguments(int argc, char *argv[])
unordered_map<string, string> getArguments(int argc, char *argv[])
{
const char splitChar = '=';
map<string, string> result;
unordered_map<string, string> result;
if (argc <= 1)
return result;
@@ -762,10 +774,10 @@ map<string, string> getArguments(int argc, char *argv[])
return result;
}
map<string, const char *> mapArguments(int argc, char *argv[])
unordered_map<string, const char *> mapArguments(int argc, char *argv[])
{
const char splitChar = '=';
map<string, const char *> result;
unordered_map<string, const char *> result;
if (argc <= 1)
return result;
@@ -804,11 +816,174 @@ map<string, const char *> mapArguments(int argc, char *argv[])
string getCompletePath(string fileName)
{
//std::filesystem::path executablePath = std::filesystem::canonical(std::filesystem::current_path()); // / std::filesystem::path(argv[0]));
std::filesystem::path exePath = std::filesystem::canonical("/proc/self/exe"); // / std::filesystem::path(argv[0]));
//std::filesystem::path fullPath = executablePath.parent_path() / "licenceData.xml";
#ifdef WINDOWS
return fileName;
#else
std::filesystem::path exePath = std::filesystem::canonical("/proc/self/exe"); // / std::filesystem::path(argv[0]));
std::filesystem::path fullPathOther = exePath.parent_path() / fileName;
//std::string fullPathStr = fullPath.string();
std::string fullPathStrOther = fullPathOther.string();
return fullPathStrOther;
#endif
}
char *getFileContent(string fileName)
{
FILE *file;
char ch;
long lSize;
size_t result;
const int fileNameLength = fileName.length();
char fileNameCh[fileNameLength] = {};
for (int i = 0; i < fileName.length(); i++)
fileNameCh[i] = fileName[i];
file = fopen(fileNameCh, "rb"); // read mode
fseek(file, 0, SEEK_END); // seek to end of file
const int size = ftell(file); // get current file pointer
fseek(file, 0, SEEK_SET);
if (file == NULL)
{
perror("Error while opening the file.\n");
return nullptr;
}
char licenceContent[size];
for (int i = 0; i < size; i++)
{
ch = fgetc(file);
licenceContent[i] = ch;
}
fclose(file);
return licenceContent;
}
void appendStringToVector(const std::string &str, std::vector<unsigned char> &charVector)
{
// Get the length of the string
size_t strLength = str.length();
// Append each character of the string to the vector
for (size_t i = 0; i < strLength; ++i)
{
charVector.push_back(static_cast<unsigned char>(str[i]));
}
}
void coutVector(std::vector<unsigned char> &charVector)
{
for (const auto &elem : charVector)
{
std::cout << elem;
}
}
uint16_t calculateCRC16(std::vector<unsigned char> &charVector)
{
const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
uint16_t crc = 0xFFFF; // Initial value
size_t length = charVector.size();
for (size_t i = 0; i < length; i++)
{
crc ^= charVector[i]; // XOR with the current data byte
for (int j = 0; j < 8; j++)
{
if (crc & 0x0001)
{
crc = (crc >> 1) ^ polynomial;
}
else
{
crc = crc >> 1;
}
}
}
return crc;
}
uint32_t bytesToDword(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
{
return static_cast<uint32_t>(byte1) |
(static_cast<uint32_t>(byte2) << 8) |
(static_cast<uint32_t>(byte3) << 16) |
(static_cast<uint32_t>(byte4) << 24);
}
uint32_t bytesToWord(uint8_t byte1, uint8_t byte2)
{
return static_cast<uint32_t>(byte1) | (static_cast<uint32_t>(byte2) << 8);
}
std::vector<unsigned char> joinVectors(const std::vector<unsigned char> &vector1, const std::vector<unsigned char> &vector2)
{
std::vector<unsigned char> result;
result.insert(result.end(), vector1.begin(), vector1.end());
result.insert(result.end(), vector2.begin(), vector2.end());
return result;
}
string readFileToString(const std::string &filename, std::size_t sizeS)
{
std::ifstream file(filename, std::ios::binary);
if (!file.is_open())
{
std::cerr << "Error: Could not open file '" << filename << "'" << std::endl;
return ""; // Return an empty string to indicate an error
}
// Read the file into a stringstream
std::stringstream buffer;
buffer << file.rdbuf();
// Get the content of the stringstream as a string
std::string fileContent = buffer.str();
// Ensure the string has at most sizeS characters
if (fileContent.size() > sizeS)
{
fileContent.resize(sizeS);
}
return fileContent;
}
bool readFile(string fileName, vector<char> &output)
{
std::ifstream file(fileName, std::ios::in | std::ios::binary);
if (!file.is_open())
{
return false;
}
char byte;
while (file.get(byte))
{
// Convert the char to unsigned char and push it into the vector
output.push_back(byte);
}
// Get the size of the file
// file.seekg(0, std::ios::end);
// streampos fileSize = file.tellg();
// file.seekg(0, std::ios::beg);
// Read the file into the buffer
// if (!file.read(reinterpret_cast<char *>(content.data()), fileSize))
// {
// throw LicenceException((int)GeneralError::FileReadError, "Chyba otevření souboru.");
// }
return true;
}