oddělení, čištění, kontrola ELC1

This commit is contained in:
2024-02-05 15:04:22 +01:00
parent 5229f16c9d
commit 37d02abd3f
54 changed files with 368 additions and 374 deletions

607
_old/LicenceELC11.cpp Normal file
View File

@@ -0,0 +1,607 @@
#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";
LicenceELC11::LicenceELC11()
{
}
LicenceELC11::LicenceELC11(LicenceIdentification &licIdentification)
: lIdentification(licIdentification)
{
}
LicenceELC11::LicenceELC11(string cisArg, string csdArg, string binaryType, string dataFileName)
{
for (unsigned int i = 0; i < cisArg.length(); i++)
this->cid[i] = cisArg[i];
for (unsigned 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
{
throw LicenceException((int)51, "Chyba při čtení xml");
}
}
/// @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 (unsigned i = 0; i < date.length(); i++)
this->sdData.manufacturerDate[i] = date[i];
// CSD
for (unsigned int i = 0; i < CSD_LENGTH; i++)
this->sdData.CSD_nibble[i] = (BYTE)csd[i];
for (unsigned 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 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
string licencePostfix; //: STRING; pomocna promenna pro kontrolu postfixu
string mainLicDescription; //: STRING(79); globalni pojmenovani licence v nesifrovane casti licence
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);
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 = 65535; // 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
{
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 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)
{
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::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 (unsigned int i = 0; i < sdCard.cidString.length(); i++)
this->cid[i] = sdCard.cidString[i]; // nutné pro původní algoritmus
for (unsigned 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;
FILE *licenceFile;
char ch;
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
if (licenceFile == nullptr)
throw LicenceException((int)Error11::LicenceReadError, "Licence read error: " + licFilePath);
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{};
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)
{
if (licenceHeader.licHeader.licSubType == cEzLic_p78ou3_SubType_10_10)
{
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)
{
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;
}
LicenceELC11::~LicenceELC11() {}

36
_old/LicenceELC31.cpp Normal file
View File

@@ -0,0 +1,36 @@
#include "licenceELC31.h"
#include "utils.h"
LicenceELC31::LicenceELC31()
{
}
LicenceELC31::LicenceELC31(LicData &licData)
{
lData = licData;
processInputConfiguration();
}
LicenceELC31::LicenceELC31(LicenceIdentification &licIdentification) : lIdentification(licIdentification)
{
}
bool LicenceELC31::processInputConfiguration()
{
return true;
}
int LicenceELC31::getDataPointsCount(int protocolId)
{
return protocolId;
}
void LicenceELC31::createLicence()
{
}
void LicenceELC31::readLicence()
{
}
LicenceELC31::~LicenceELC31() { }

281
_old/licenceELC11.h Normal file
View File

@@ -0,0 +1,281 @@
#ifndef PLC_LICENCE11_H
#define PLC_LICENCE11_H
#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <wchar.h>
#include <time.h>
#include <map>
#include <stdint.h>
#include "licenceCommon.h"
#include "SDCard.h"
using namespace std;
#define MAX_LICENCE_COUNT 100
enum InputLicenceType
{
EOSEOV = 1
};
enum BinaryGenerationType
{
Base64Cout = 1,
File = 2
};
enum PlcLicenceType
{
LicenceOther = 0,
LicenceEov = 1
};
enum LidIdType
{
Ddts = 1,
EovOsv = 2
};
enum PrefixType
{
ELC1 = 1
};
typedef uint32_t DWORD;
typedef uint16_t WORD;
typedef uint8_t BYTE;
typedef uint32_t UDINT;
typedef uint32_t DATE;
typedef uint8_t USINT;
typedef int32_t DINT;
typedef uint16_t UINT;
typedef int16_t INT;
/// @brief identifikace licence
typedef struct LicenceIdent
{
WORD licPrefixType = 0; // WORD; typ licencniho souboru - pro kazdy prefig je jiny typ souboru a jiny zpusob zpracovani dat [sifrovani, podpis, komprese, ...]
WORD licHeaderType = 0; //: WORD; typ hlavicky kriptovane casti licencniho souboru
WORD licDataType = 0; //: WORD; typ licence - pro kazdou hlavicku jsou samostatne typy licenci - mohou byt i shodne s typem jine hlavicky
WORD licSubType = 0; //: WORD; slouceny typ hlavicku a typ licence => typ hlavicky * 256 + typ licence
WORD licIDType = 0; //: WORD; id aplikace, pro kterou je licence urcena => 1 = ddts, 2 = eov-osv
BYTE licPostfix = 0; //: BYTE; rozliseni licence pro stejny typ - napr. pokud mam 2x SW pro DRT na 2 nezavisle ED
} LicenceIdent;
/// @brief struktura pro přípravu dat na generování
typedef struct LicenceSourceData
{
BYTE startGen; // na nabeznou hranu se vygeneruje licence
BYTE loadSD; //: BOOL; na nabeznou hranu se nacte SD karta
// zadavane hodnoty
BYTE licType_id; // vybrany typ licence
char licDescription1[40] = {}; //: STRING(39); jmeno stanice
char licDescription2[20] = {}; //: STRING(19); jmeno rozvadece
BYTE licPostfix; // rozliseni licence pro stejny typ - napr. pokud mam 2x SW pro DRT na 2 nezavisle ED
BYTE enInit; //: BOOL; inicializace (promazani) adresare pro licence
// interne generovane hodnoty
WORD licType; //: WORD; hlavicka licence
BYTE licIdOk; //: BOOL; korektne zvoleny typ licence
string licPostfixIdent; //[2]; //: STRING(2); vygenerovany postfix z cisla pro rozliseni postfixu v souborech a textech
} LicenceSourceData;
/// @brief struktura obsahující dodatečné informace k licenci
typedef struct PlcData
{
string plcType = "";
string licenceType = ""; // typ
string licenceVersion = "1";
string licenceName = ""; // název
string station = ""; // stanice
string distributor = ""; // rozvadec
} PlcData;
/*
MID (Manufacturer ID): 8 bits - Identifies the manufacturer of the SD card.
OID (OEM/Application ID): 16 bits - Identifies the OEM and application-specific information.
PNM (Product Name): 40 bits - A string representing the product name of the SD card.
PRV (Product Revision): 8 bits - The product revision/version.
PSN (Product Serial Number): 32 bits - A unique serial number assigned to the SD card during manufacturing.
MDT (Manufacturing Date): 12 bits - Represents the manufacturing date of the SD card.
CRC (CRC7 Checksum): 7 bits - A cyclic redundancy check for error detection.
unused: 4 bits - Reserved for future use.
*/
/// @brief struktura pro načtení CIS a CSD dat
typedef struct SDData
{
BYTE isCorrectLoad = 0; // SD karta je korektne nactena //bool vs byte ?
BYTE CID_nibble[32] = {0}; // surova data CID ze souboru
BYTE CID[16] = {0}; // prekodovane CID informace
BYTE manufacturerID = 0; // ID vyrobce 1B -> Byte 15
char oemID[2] = {}; // ID aplikace/oem 2B -> Byte 13-14 // oemID: !!STRING(3);
char name[5] = {}; // jmeno produktu 5B -> Byte 8-12 !!STRING(6);
BYTE productRevision_hw = 0;
BYTE productRevision_sw = 0;
float productRevision = 0; // revize produktu 1B [bcd sh] -> Byte 7, bity 0-3 = revize HW, bity 4-7 = revize SW
DWORD serialNumber = 0; // seriove cislo karty 4B -> Byte 3-6
WORD manufacturerDate_year = 0;
BYTE manufacturerDate_month = 0;
char manufacturerDate[10] = {}; //: STRING(10); // datum vyroby 2B [bcd -yym] -> Byte 1-2, bity 0-3 = mesic, bity 4-11 = posledni cislice roku or roku 2000, bity 12-15 nepouzito
BYTE CRCOK = 0; // CRC 1B -> Byte 0, bity 1-7, bit 0 je vzdy = 1
BYTE CSD_nibble[32] = {}; //: ARRAY [0..31] OF BYTE; // surova data CSD ze souboru
BYTE CSD[16] = {}; //: ARRAY [0..15] OF BYTE; // prekodovane CSD informace
UDINT cardSize = 0; //: UDINT; // velikost SD karty
BYTE cardGSize = 0; // prepocitana velikost na GB
} CidData;
// nekodovana cast licence
/// @brief nekryptovaná hlavička licence
typedef struct LicenceDataMainHeaderELC
{
BYTE licType = 0;
; // typ licence => duplicitni polozka s hlavickou kodovane casti licence - pouze pro ucely dekodovani dat
BYTE dummy1 = 0;
WORD licSubType = 0; // horni byte = typ hlavicky kodovane casti, spodni byte = typ dat polozkove casti => duplicitni casti s id a hlavickou kodovane casti - pouze pro ucely dekodovani
char description[80] = {}; // viditelny popis licincniho souboru
UDINT sizeData = 0; // velikost kodovane casti licence v Bytech
} LicenceDataMainHeaderELC;
// hlavní struktura licence
typedef struct LicenceDataMainELC
{
// prefix MUSI zustat jako prvni prvek struktury a MUSI byt typu DWORD
DWORD prefix = 0; // urcuje strukturu dat citelne casti licencniho souboru [teto struktury] + zpusob sifrovani, dig, podpis, kompresi... dat
LicenceDataMainHeaderELC licHeader {}; // nekodovana cast licence
} LicenceDataMain;
// polozkova cast licence verze 1.0
typedef struct LicenceDataItem
{
WORD protoId = 0; // id protokolu pro ktery je licence
WORD licCount = 0; // pocet datovych bodu licence
DWORD data1 = 0; // doplnkove nahodne cislo, slouzi pro overeni licence v runtime
} LicenceDataItem;
// identifikace kodovane casti licence - !!! MUSI yustat pro vsechny verze STEJNA !!!
typedef struct LicenceDataId
{
WORD version = 0; // verze hlavicky
WORD rez = 0;
UDINT cardSize = 0;
} LicenceDataId;
typedef struct LicenceDataHeader
{
BYTE licType = 0; // typ licence => 0...neznamy (chyba), 1...DDTS, 2...EOV-OSV
BYTE licReserve = 0; // rezerva
WORD licVersion = 0; //: WORD; verze polozkove casti licence
DATE licDate = 0; // datum vygenerovani licence
char licDescription1[40] = {}; // licDescription1: STRING(39); stanice, pro kterou byla licence generovana
char licDescription2[20] = {}; // STRING(19); rozvadec, pro ktery byla licence generovana
USINT licCount = 0; // aktivni pocet dat polozkove casti licence
BYTE licDummy = 0; // rezerva
WORD licReservew = 0; // rezerva
} LicenceDataHeader;
// kodovana cast licence verze 1.1 s polozkovou casi licence verze 1.0
typedef struct LicenceData
{
LicenceDataId id {}; // id !!! MUSI zustat na PRVNIM miste struktury
LicenceDataHeader header{} ;
LicenceDataItem items[MAX_LICENCE_COUNT] = {}; // polozkova cast licence
WORD dummy = 0; // pro zarovnani struktur - jinak nebude fungovat vypocet a kontrola CRC !!!
WORD crc = 0; // kontrolni kod - !!! MUSI zustat na konci struktury
} LicenceData;
typedef struct LicenceRetData
{
BYTE retCode = 0; // navratovy kod funkce pro nacteni SD
DINT subCode = 0; // doplnkova informace chyby
std::string text = ""; // textovy popis navratove hodnoty
bool isDone = false; // operace korektne dokoncena
} LicenceRetData;
typedef struct CryptData
{
bool initDone = false;
DWORD cryptDataAddress = 0; // adresa na data, ktera se maji cryptovat
UINT cryptDataSize = 0; // velikostdat, ktera semaji cryptovat
BYTE aesInitVector[15] = {0}; //] : ARRAY [0..14] OF BYTE;// AES 128 bit IV
BYTE aesKey[32] = {0}; // : ARRAY [0..31] OF BYTE; // AES 256 bit key
DINT aesRetVal = 0; // navratova hodnota AES
DWORD retDataAddress = 0; // adresa na ulozeni cryptovana dat
UINT retDataSize = 0; // velikost cryptovanych dat
LicenceData *licenseData;
} CryptData;
/// @brief licence class
class LicenceELC11
{
enum class Error11
{
SDCardReadError = 50,
LicenceReadError = 51,
LicenceSizeMismatch = 52,
LicenceSizeCardMismatch = 53,
LicenceMismatch = 54,
ItemsCountMismatch = 61
};
// unordered_map<Error11, string> map11Errors = {
// {Error11::SDCardReadError, "Nepodařilo se načíst SD kartu."},
// {Error11::ItemsCountMismatch, "Nesouhlasí počet položek licence."}
// };
private:
SDCard sdCard;
string cidString = "";
char cid[32] = {};
string csdString = "";
char csd[32] = {}; // CSD
string stationName; // name of station
string distributor; // name of switch
const char *dataFileName; // name of xml containing data (if not taken from commandline)
WORD licType = 2; // type of licence
BinaryGenerationType binaryGeneration = BinaryGenerationType::Base64Cout; //typ generování binárního souboru
string dataLicenceType = ""; //type of licence from xmlFile;
string dataLicenceVersion = ""; //version type of licence from xmlFile;
string dataCryptoVersion = ""; //version of crypting from xmlFile
string dataGenerationType = ""; //version of dataGeneration from xmlFile
string dataLicenceDataFileName = ""; //name of licence file to read
CryptData cryptData; // structure for encryp
CidData sdData; // data loaded from SD card
void processConfigFile(string &dataFileName); //process data from config file
void getSDData(); // reads SD card
string getLicenceName(BYTE licPostfix); // get proper licencename
string getLicenceName();
void initCrypto();
bool createEosEovLicence(); // create licence for EOV_OSV
bool readEosEovLicence(string dataFileName);
LicenceIdentification lIdentification;
public:
string operationErrors = "";
ErrorMessage errorMessage;
string cid_cdsPath = ""; //"c:\\_projects\\LicenceGenerator\\output\\"; ///sys/block/mmcblk0/device/
string licenceFilePath = ""; //"c:\\_projects\\LicenceGenerator\\output\\";
LicenceELC11();
~LicenceELC11();
LicenceELC11(string cid, string csd, string binaryType, string dataFileName);
LicenceELC11(LicenceIdentification & licIdentification);
bool createLicence(); // creates licence
bool readLicence(LicenceInfoGeneral * licences);
};
#endif

585
_old/licenceELC21.cpp Normal file
View File

@@ -0,0 +1,585 @@
#include "licenceELC21.h"
#include "utils.h"
#include "SDCard.h"
#include "pugixml.hpp"
LicenceELC21::LicenceELC21()
{
}
LicenceELC21::LicenceELC21(LicenceIdentification &licIdentification, LicData &licData)
: lIdentification(licIdentification), lData(licData)
{
}
LicenceELC21::LicenceELC21(LicenceIdentification &licIdentification): lIdentification(licIdentification)
{
}
LicenceELC21::LicenceELC21(LicData &licData): lData(licData)
{
if (processInputConfiguration() == false) throw LicenceException((int)Error21::LicenceReadError, "Chyba při čtení licence");
}
bool LicenceELC21::createLicence()
{
getLicenceItems();
getHeader();
sdCard = SDCard(lData.cid, lData.csd);
if (sdCard.isLoaded == false) throw LicenceException((int)Error21::SDCardReadError, "Chyba při čtení SD karty, cesta: " + cid_cdsPath);
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;
vector<unsigned char> privateContent;
vector<unsigned char> privateContentEncrypted;
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);
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 (unsigned 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);
string licfileName = getLicenceName();
std::ofstream outputFile(licfileName, std::ios::out | std::ios::binary);
// Check if the file is open
if (!outputFile.is_open())
{
throw LicenceException((int)GeneralError::FileOpenError, "Chyba při zakládání souboru licence: " + cid_cdsPath);
}
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)
{
// 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;
vector<char> content;
if (readFile(licFilePath, content) == false)
{
throw LicenceException((int)GeneralError::FileOpenError, "Chyba otevření souboru licence: " + licFilePath);
}
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]);
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());
vector<unsigned char> privateContentDecrypted;
privateContentDecrypted = decryptPrivateContent(encryptedPart);
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]);
//~~~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 += 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));
}
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
{
errorMessage.code = (int)Error21::LicenceMismatch;
errorMessage.message = "ERROR MISSING licenceType";
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;
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("\",");
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\":[");
lIdentification.licItemsCount = std::distance(lData.doc->child("licence").child("items").begin(), lData.doc->child("licence").child("items").end());
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] = {};
BYTE aesKey[32] = {};
LicenceELC21::initVector(initVector, aesKey);
unsigned char encrypted[10000] = {};
const unsigned char *plainTextArray = content.data();
int finalEncryptedLength = encrypt(plainTextArray, content.size(), aesKey, initVector, encrypted);
if (finalEncryptedLength <= 0) throw LicenceException((int)GeneralError::EncryptError, "Chyba při kryptování.");
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);
if (decrypted_len <= 0) throw LicenceException((int)GeneralError::DecryptError, "Chyba při dekryptování.");
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()
{
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 = {8, 13, 11, 9, 7, 11, 10, 13, 5, 20, 19};
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(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));
}
}
else
{
errorMessage.code = 1;
errorMessage.message = "Error: Null pointer!";
return false;
}
return true;
}
LicenceELC21::~LicenceELC21() {}

130
_old/licenceELC21.h Normal file
View File

@@ -0,0 +1,130 @@
#ifndef PLC_LICENCE21_H
#define PLC_LICENCE21_H
#include "utils.h"
#include <stdint.h>
#include <unordered_map>
#include "licenceCommon.h"
#include "pugixml.hpp"
#include "SDCard.h"
using namespace std;
class LicenceELC21
{
struct LicData
{
string station = "";
string distributor = "";
string licenceName = "";
string projectDescription = "";
string cid = ""; // CID z SD karty
string csd = ""; // CSD z SD karty
string uid = ""; // jedinečný identifikátor z jiného systému
pugi::xml_document *doc;
};
public:
ErrorMessage errorMessage;
LicenceInfo21 licenceInfo;
string cid_cdsPath = ""; //"c:\\_projects\\LicenceGenerator\\output\\"; ///sys/block/mmcblk0/device/
string licenceFilePath = ""; //"c:\\_projects\\LicenceGenerator\\output\\";
LicenceELC21();
~LicenceELC21();
LicenceELC21(LicenceIdentification &licIdentification, LicData &licData);
LicenceELC21(LicenceIdentification &licIdentification);
LicenceELC21(LicData &licData);
bool createLicence();
bool readLicence(LicenceInfoGeneral *licences);
int getDataPointsCount(int protocolId);
bool getLicenceInfo(void *ptr);
bool getLicenceItemInfo(int protocolId, void *returnItemStructure);
enum class Error21
{
SDCardReadError = 50,
LicenceReadError = 51,
LicenceSizeMismatch = 52,
LicenceSizeCardMismatch = 53,
LicenceMismatch = 54,
ItemsCountMismatch = 61
};
unordered_map<Error21, string> map21Errors = {
{Error21::SDCardReadError, "Nepodařilo se načíst SD kartu."},
{Error21::ItemsCountMismatch, "Nesouhlasí počet položek licence."},
{Error21::LicenceSizeMismatch, "Nesouhlasí velikost souboru licence."},
{Error21::LicenceSizeCardMismatch, "Nesouhlasí velikost SD karty."},
{Error21::LicenceMismatch, "Nesouhlasí licence."},
{Error21::ItemsCountMismatch, "Nesouhlasí počet položek licence."},
};
struct LicenceId
{
char licIdent[5] = {'E', 'L', 'C', '0', '_'};
};
// struct __attribute__((__packed__)) LicencePublicHeader
struct LicenceIdentDataHeader
{
BYTE licenceType = 0; // EOSEOV, DRT ...
BYTE licenceTypeVersion = 1; // verze licence, urcuje nuance sifrování a pojmenování souborů
BYTE licenceIndex = 0; // puvodní post fix, identifikátor pro více licencí
BYTE compatibilityVersion = 1; // udava verzi komplet PrivateContent
BYTE licItemCount = 0; // počet licenčních bodů
WORD publicHeaderLength = 0; // délka veřejné hlavičy
WORD cardSize = 0; // velikost SD karty
DWORD serialNumber = 0; // seriove cislo karty
};
///
struct licDataItem
{
WORD protoId = 0; // id protokolu pro ktery je licence
WORD licCount = 0; // pocet datovych bodu licence
char dummy[64] = {}; // dummy pro větší velikost licence v případě méně licenčních bodů
};
struct PublicHeader
{
string version = "";
string projectDescription = "";
string date = "";
string licenceType = "";
int crc = 0;
};
struct PrivateContent // privátní šifrovaná část
{
LicenceIdentDataHeader licenceIdentHeader;
vector<licDataItem> dataItems;
WORD crc = 0;
};
struct LicenceBody
{
LicenceId licId;
LicenceIdentDataHeader licenceIdentHeader;
string publicHeader = ""; // JSON
PrivateContent privateContent;
};
private:
int licItemCount = 0;
LicenceBody licBody;
LicenceIdentification lIdentification;
LicData lData;
SDCard sdCard;
void getHeader();
string getVersion(int middleVersion);
void getLicenceItems();
bool processInputConfiguration();
vector<unsigned char> cryptPrivateContent(const std::vector<unsigned char> &content);
vector<unsigned char> decryptPrivateContent(const std::vector<unsigned char> &content);
void initVector(BYTE (&iVector)[], BYTE (&key)[]);
string getLicenceName();
};
#endif

43
_old/licenceELC31.h Normal file
View File

@@ -0,0 +1,43 @@
#ifndef PLC_LICENCE31_H
#define PLC_LICENCE31_H
#include <stdint.h>
#include <iostream>
#include <vector>
#include "utils.h"
#include "licenceCommon.h"
#include "pugixml.hpp"
using namespace std;
class LicenceELC31
{
struct LicData
{
string station = "";
string distributor = "";
string licenceName = "";
string projectDescription = "";
string cid = ""; // CID z SD karty
string csd = ""; // CSD z SD karty
string uid = ""; // jedinečný identifikátor z jiného systému
pugi::xml_document *doc;
};
LicData lData;
bool processInputConfiguration();
LicenceIdentification lIdentification;
public:
LicenceELC31();
~LicenceELC31();
LicenceELC31(LicData & licData);
LicenceELC31(LicenceIdentification & licIdentification);
void createLicence();
void readLicence();
int getDataPointsCount(int protocolId);
};
#endif