This commit is contained in:
2024-01-24 08:25:44 +01:00
parent f260e92596
commit 36a799057c
42 changed files with 926 additions and 2313 deletions

View File

@@ -13,7 +13,7 @@
"windowsSdkVersion": "10.0.22000.0",
"compilerPath": "g++.exe",
// "cStandard": "c99",
"cppStandard": "c++20",
"cppStandard": "c++20", //ex=c++20
"intelliSenseMode": "gcc-x86"
}
],

17
.vscode/settings.json vendored
View File

@@ -68,7 +68,22 @@
"map": "cpp",
"csignal": "cpp",
"filesystem": "cpp",
"list": "cpp"
"list": "cpp",
"array": "cpp",
"*.tcc": "cpp",
"cstdarg": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"unordered_map": "cpp",
"functional": "cpp",
"memory_resource": "cpp",
"numeric": "cpp",
"random": "cpp",
"string_view": "cpp",
"numbers": "cpp",
"span": "cpp",
"cinttypes": "cpp",
"variant": "cpp"
},
"C_Cpp.errorSquiggles": "enabledIfIncludesResolve"
}

View File

@@ -7,8 +7,8 @@
CXX = g++
# define any compile-time flags
# CXXFLAGS := -std=c++17 -Wall -Wextra -g -lssl -lcrypto
CXXFLAGS := -Wall -Wextra -g -lssl -lcrypto -w
# CXXFLAGS := -std=c++17 -Wall -Wextra -g -lssl -lcrypto -w
CXXFLAGS := -Wall -Wextra -g -lssl -lcrypto
# define library paths in addition to /usr/lib
# if I wanted to include libraries not in /usr/lib I'd specify

View File

@@ -8,7 +8,7 @@ CXX = g++
# define any compile-time flags
# CXXFLAGS := -std=c++17 -Wall -Wextra -g -lssl -lcrypto
CXXFLAGS := -Wall -Wextra -g -lssl -lcrypto -w
CXXFLAGS := -Wall -Wextra -g -lssl -lcrypto -std=c++11
# define library paths in addition to /usr/lib
# if I wanted to include libraries not in /usr/lib I'd specify

View File

@@ -45,6 +45,7 @@ class SDCard
uint8_t CSD[16] = {}; //: ARRAY [0..15] OF BYTE; // prekodovane CSD informace
uint32_t cardSize = 0; //: UDINT; // velikost SD karty
uint8_t cardGSize = 0; // prepocitana velikost na GB
bool crcCorrect = false;
};
bool readSDCard();

View File

@@ -15,8 +15,6 @@ const int cidSize = 32;
const int csdSize = 32;
const int generatorVersion = 1;
enum class GeneralError
{
GeneralError = 1,
@@ -27,18 +25,11 @@ enum class GeneralError
LicenceTypeNotImplemented = 6,
CompatibilityTypeNotImplemented = 7,
ELCMismatch = 8,
CRCMismatch = 9
CRCMismatch = 9,
EncryptError = 10,
DecryptError = 11
};
// map<GeneralError, string> mapGeneralErrors = {
// // 1,"test"
// // {CommonError::GeneralError, "Obecná chyba."},
// // {CommonError::FileReadError, "Chyba čtení souboru."},
// // {CommonError::FileReadError, "Chyba zápisu souboru."},
// // {CommonError::ELCNotImplemented, "ELC není implementováno."},
// // {CommonError::LicenceTypeNotImplemented, "Typ licence není implementován"}
// };
enum class ELCType
{
ELC1 = 1,

View File

@@ -146,7 +146,7 @@ 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
LicenceDataMainHeaderELC licHeader {}; // nekodovana cast licence
} LicenceDataMain;
// polozkova cast licence verze 1.0
@@ -181,9 +181,9 @@ typedef struct 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
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;
@@ -247,8 +247,6 @@ class LicenceELC11
string dataGenerationType = ""; //version of dataGeneration from xmlFile
string dataLicenceDataFileName = ""; //name of licence file to read
//InputLicenceType dataLicenceType = InputLicenceType::EOSEOV;
CryptData cryptData; // structure for encryp
CidData sdData; // data loaded from SD card
@@ -275,7 +273,6 @@ public:
LicenceELC11(LicenceIdentification & licIdentification);
bool createLicence(); // creates licence
bool readLicence(string dataFileName, string licenceType, string licenceVersion, string cidArg, string csdArg);
bool readLicence(LicenceInfoGeneral * licences);

View File

@@ -1,11 +1,9 @@
#ifndef PLC_LICENCE21_H
#define PLC_LICENCE21_H
#include <stdint.h>
#include <iostream>
#include <unordered_map>
#include <vector>
#include "utils.h"
#include <stdint.h>
#include <unordered_map>
#include "licenceCommon.h"
#include "SDCard.h"
@@ -14,6 +12,23 @@ using namespace std;
class LicenceELC21
{
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 & icData);
LicenceELC21(LicenceIdentification & licIdentification);
LicenceELC21(LicData & icData);
bool createLicence();
bool readLicence(LicenceInfoGeneral * licences);
int getDataPointsCount(int protocolId);
bool getLicenceInfo(void * ptr);
bool getLicenceItemInfo(int protocolId, void *returnItemStructure);
enum class Error21
{
@@ -34,14 +49,12 @@ class LicenceELC21
{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 ...
@@ -102,26 +115,6 @@ class LicenceELC21
void initVector(BYTE (&iVector)[], BYTE (&key)[]);
string getLicenceName();
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 & icData);
LicenceELC21(LicenceIdentification & licIdentification);
LicenceELC21(LicData & icData);
bool createLicence();
bool readLicence(LicenceInfoGeneral * licences);
int getDataPointsCount(int protocolId);
bool getLicenceInfo(int protocolId, void * ptr);
bool getLicenceItemInfo(int protocolId, void *returnItemStructure);
};
#endif

View File

@@ -13,6 +13,8 @@ class LicenceELC31
{
LicData lData;
bool processInputConfiguration();
LicenceIdentification lIdentification;
public:
LicenceELC31();
@@ -22,7 +24,6 @@ class LicenceELC31
void createLicence();
void readLicence();
int getDataPointsCount(int protocolId);
bool getLicenceInfo(int protocolId, void * ptr);
};
#endif

View File

@@ -18,17 +18,6 @@
using namespace std;
struct InitStructure
{
int elcType = 0;
int licenceType = 0;
int licenceVersion = 0;
int licenceIndex = 0;
int compatibility = 0;
string licenceFilePath = "";
string cid_csd_filePath = "";
};
class LicenceGenerator
{
@@ -44,14 +33,8 @@ public:
LicenceGenerator();
~LicenceGenerator();
LicenceGenerator(map<string, string> &arguments);
// LicenceGenerator(string cid, string csd, string dataFileName, string binaryType);
LicenceGenerator(string uid, string cid, string csd, string dataFileName);
LicenceGenerator(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility);
bool init(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility);
bool init(InitStructure &initStructure);
bool initread(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility);
bool initread(InitStructure &initStructure);
void createLicenceFile();
void readLicenceFile();

60
include/licenceReader.h Normal file
View File

@@ -0,0 +1,60 @@
#ifndef LICENCE_READER_H_
#define LICENCE_READER_H_
#include "utils.h"
// #include "licenceCommon.h"
#include "licenceELC11.h"
#include "licenceELC21.h"
#include "licenceELC31.h"
using namespace std;
struct InitStructure
{
int licenceType = 0;
int licenceVersion = 0;
int licenceIndex = 0;
int compatibility = 0;
string licenceFilePath = "";
string cid_csd_filePath = "";
};
class LicenceReader
{
public:
int elcSwitchType;
string operationErrors = "";
bool argumentsCorrect = false;
ErrorMessage error;
LicenceELC11 *licence11;
LicenceELC21 *licence21;
LicenceELC31 *licence31;
LicenceReader();
~LicenceReader();
bool init(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility);
bool init(int elcType, InitStructure &initStructure);
bool initread(int elcType, int licenceType, int licenceVersion, int licenceIndex, int compatibility);
bool initread(int elcType, InitStructure &initStructure);
void readLicenceFile();
bool getLicenceInfo(void *returnStructure);
bool getLicenceItemInfo(int protocolId, void *returnItemStructure);
LicenceInfoGeneral licenceInfo;
private:
LicenceIdentification licIdentification;
LicData licData;
string configFileName = "";
void *licence = nullptr;
void readLicenceELC1();
void readLicenceELC2();
void readLicenceELC3();
};
#endif

View File

@@ -1,258 +0,0 @@
#ifndef PLC_LICENCE_H
#define PLC_LICENCE_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>
using namespace std;
#define MAX_LICENCE_COUNT 100
enum InputLicenceType
{
EOSEOV = 1
};
enum BinaryGenerationType
{
Base64Cout = 1,
File = 2
};
enum LicenceType
{
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 PlcLicence
{
private:
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
//InputLicenceType dataLicenceType = InputLicenceType::EOSEOV;
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
void initCrypto();
bool CreateEosEovLicence(); // create licence for EOV_OSV
bool ReadEosEovLicence(string dataFileName);
public:
string operationErrors = "";
PlcLicence();
PlcLicence(map<string, string> & arguments);
PlcLicence(string cid, string csd, string binaryType, string dataFileName);
bool CreateLicence(); // creates licence
bool ReadLicence(string dataFileName, string licenceType, string licenceVersion, string cidArg, string csdArg);
// bool CreateEosEovLicence();
};
#endif

View File

@@ -1,27 +1,17 @@
#define LINUX 1
//#define LINUX 1
#define WINDOWS 1
#ifndef UTILS_H_
#define UTILS_H_
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <chrono>
#include <bitset>
#include <unordered_map>
#include <filesystem>
#include <vector>
#define PEM_BUFSIZE_TEXT 1024
#define BitVal(data, y) ((data >> y) & 1) /** Return Data.Y value **/
#define SetBit(data, y) data |= (1 << y) /** Set Data.Y to 1 **/
#define ClearBit(data, y) data &= ~(1 << y) /** Clear Data.Y to 0 **/
#define TogleBit(data, y) (data ^= BitVal(y)) /** Togle Data.Y value **/
#define Togle(data) (data = ~data) /** Togle Data value **/
#define PEM_BUFSIZE_TEXT 1024
#include <chrono>
#include <format>
#include <libgen.h> // dirname
#include <climits>
typedef uint8_t BYTE;
typedef uint16_t WORD;
@@ -35,45 +25,32 @@ struct DateAndTime {
uint16_t time; // TIME data type in CODESYS
};
void TestFunction(int);
void generatePause();
string getXmlContentFromString(string source, string xmlTag);
float byteArrayToFloat(const BYTE* byteArray);
std::string right(const std::string& sourceString, size_t numChars);
std::tm dt_to_date(const std::chrono::system_clock::time_point& tp);
void getCharsFromString(string source, char *charArray);
std::string parseCID(const std::string& cidHex);
void bitsToCharArray(const std::string& bitsStr, char* charArray);
uint16_t calculateCRC16(const uint8_t* data, size_t length);
uint16_t calculateCrc(const uint8_t* data, size_t length);
WORD getCurrentDateAsCODESYSDate();
DWORD getCurrentDateAsCODESYSDateDword();
DateAndTime getCurrentDateTimeAsCODESYSDateTime();
uint16_t convertToCODESYSDate(int day, int month, int year);
uint16_t convertToCODESYSTime(int hour, int minute);
DATE getLicDate();
string getDate();
int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext);
bool CompareFiles(const char *fileName, const char *fileName1);
unsigned short crc16(const unsigned char* data_p, unsigned char length);
int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext);
string convertToString(char* a, int size);
std::string base64_encode_ai(const std::string &input);
std::string base64_decode_ai(const std::string &encoded);
string base64_encode_ai(const std::string &input);
unordered_map<string, string> getArguments(int argc, char *argv[]);
unordered_map<string, const char*> mapArguments(int argc, char *argv[]);
char* getCharArray(string source);
void getCharsFromString1(string source, char *charArray);
void getCharsFromString(string& source, char *charArray, int length);
void getCharsFromString(string& source, char *charArray, size_t length);
string getCompletePath(string fileName);
char* getFileContent(string fileName);
void appendStringToVector(const std::string& str, std::vector<unsigned char>& charVector);
void coutVector (std::vector<unsigned char>& charVector);
uint16_t calculateCRC16(std::vector<unsigned char>& charVector);
uint32_t bytesToDword(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4);
uint32_t bytesToWord(uint8_t byte1, uint8_t byte2);
vector<unsigned char> joinVectors(const std::vector<unsigned char>& vector1, const std::vector<unsigned char>& vector2);
string readFileToString(const std::string& filename, std::size_t sizeS);
bool readFile(string fileName, vector<char> &output);
#endif

5
output/cis Normal file
View File

@@ -0,0 +1,5 @@
0353445355313647801b1a9f6600c747
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

View File

@@ -1 +1 @@
licenceGenerator.exe -cid=9f544930303030300000000b47015423 -csd=400e00325b5900003a0d7f800a40008d -outputType=base64 -configFileName=licData.xml
licenceGenerator.exe -cid=0353445355313647801b1a9f6600c747 -csd=400e00325b59000076b27f800a404013 -outputType=file -configFileName=licData.xml

View File

@@ -1 +1 @@
licenceGenerator.exe -cid=9f544930303030300000000b47015423 -csd=400e00325b5900003a0d7f800a40008d -outputType=file -configFileName=licData.xml
licenceGenerator.exe -cid=0353445355313647801b1a9f6600c747 -csd=0353445355313647801b1a9f6600c747 -outputType=file -configFileName=licData.xml

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -9,24 +9,29 @@
<items>
<item>
<name>Položka licence 1</name>
<protoId>666</protoId>
<protoId>111</protoId>
<dataPointsCount>100</dataPointsCount>
</item>
<item>
<name>Položka licence 2</name>
<protoId>777</protoId>
<protoId>222</protoId>
<dataPointsCount>200</dataPointsCount>
</item>
<item>
<name>Položka licence 3</name>
<protoId>888</protoId>
<protoId>333</protoId>
<dataPointsCount>300</dataPointsCount>
</item>
<item>
<name>Položka licence 3</name>
<protoId>999</protoId>
<protoId>444</protoId>
<dataPointsCount>1600</dataPointsCount>
</item>
<item>
<name>Položka licence 4</name>
<protoId>555</protoId>
<dataPointsCount>1999</dataPointsCount>
</item>
</items>
</licence>

Binary file not shown.

View File

@@ -1,78 +1,28 @@
#include <stdio.h>
#include "utils.h"
#include "licenceGenerator.h"
#include "licenceReader.h"
#include "licenceCommon.h"
/// @brief hlavní funkce
/// @param argc
/// @param argv parametry pro generování licence
/// @return
int main(int argc, char *argv[])
int main5(int argc, char *argv[])
{
try
{
/* code */
unordered_map<string, string> arguments = getArguments(argc, argv);
// try
// {
// unordered_map<string, string> arguments = getArguments(argc, argv);
// LicenceGenerator generatorOld = LicenceGenerator(arguments["-uid"], arguments["-cid"], arguments["-csd"], arguments["-configFileName"]);
// generatorOld.createLicenceFile();
// return SUCCES;
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 = "";
initStructure.cid_csd_filePath = "";
// //verze #1: načtení kompletní licence a zobrazení
// if (licenceGenerator.init(initStructure))
// {
// LicenceInfo21 info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
// int protocolId = 345;
// if (licenceGenerator.getLicenceInfo(protocolId, &info))
// {
// std::cout << "Počet licenčních bodů pro : " << protocolId << ": " << info.reqDataPointsCount << std::endl;
// if (info.licences.count(protocolId) > 0) cout << "počet z vectoru pro : " << protocolId << 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
// catch (...)
// {
// cerr << "Došlo k chybě: " << licenceGenerator.error.message;
// cerr << "Obecná chyba\n";
// }
// verze #2 : iterace pro kazdý bod zvlášť
if (licenceGenerator.initread(initStructure))
{
int protocolId = 888;
LicenceItem21 info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
if (licenceGenerator.getLicenceItemInfo(protocolId, &info))
{
std::cout << "Počet licenčních bodů pro " << info.protocolId << ": " << info.dataPointsCount << std::endl;
}
else
cerr << "Došlo k chybě: " << licenceGenerator.error.message;
}
else
{
cerr << "Došlo k chybě: " << licenceGenerator.error.message;
}
}
catch (...)
{
cerr << "Obecná chyba\n";
}
system("pause");
// system("pause");
return SUCCES;
}

View File

@@ -51,7 +51,6 @@ 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};
const string eoseovLicenceType = "EOV_OSV";
// enum LicenceType { EovOsv = 1 };
LicenceELC11::LicenceELC11()
{
@@ -65,9 +64,9 @@ LicenceELC11::LicenceELC11(LicenceIdentification &licIdentification)
LicenceELC11::LicenceELC11(string cisArg, string csdArg, string binaryType, string dataFileName)
{
for (int i = 0; i < cisArg.length(); i++)
for (unsigned int i = 0; i < cisArg.length(); i++)
this->cid[i] = cisArg[i];
for (int i = 0; i < csdArg.length(); i++)
for (unsigned int i = 0; i < csdArg.length(); i++)
this->csd[i] = csdArg[i];
this->stationName = "";
@@ -111,7 +110,7 @@ void LicenceELC11::processConfigFile(string &dataFileName)
}
else
{
std::cerr << "Unable to open the config file." << std::endl;
throw LicenceException((int)51, "Chyba při čtení xml");
}
}
@@ -147,14 +146,14 @@ void LicenceELC11::getSDData()
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++)
for (unsigned i = 0; i < date.length(); i++)
this->sdData.manufacturerDate[i] = date[i];
// CSD
for (int i = 0; i < CSD_LENGTH; i++)
for (unsigned int i = 0; i < CSD_LENGTH; i++)
this->sdData.CSD_nibble[i] = (BYTE)csd[i];
for (int i = 0; i < cnibblescount / 2; 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]];
@@ -218,8 +217,6 @@ string LicenceELC11::getLicenceName()
{
string result = "";
char prefixChar = 97;
int licType = (int)lIdentification.licLicenceType;
int lVersion = lIdentification.licenceVersion;
int licIndex = lIdentification.licenceIndex;
// natvrdo, stará ELC
@@ -305,19 +302,14 @@ bool LicenceELC11::createEosEovLicence()
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
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
USINT generation = 2; //: USINT; verze SW pro licenceřř
PlcData plcData;
plcData.licenceName = "Licence";
@@ -337,7 +329,7 @@ bool LicenceELC11::createEosEovLicence()
getCharsFromString(plcData.distributor, dataToFile.header.licDescription2);
}
LicenceIdent licIdent;
LicenceIdent licIdent{};
licIdent.licPrefixType = licSourceData.licType >> 12;
licIdent.licHeaderType = licSourceData.licType >> 8 & 0x000F;
licIdent.licDataType = licSourceData.licType >> 4 & 0x000F;
@@ -351,8 +343,6 @@ bool LicenceELC11::createEosEovLicence()
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)
@@ -413,10 +403,6 @@ bool LicenceELC11::createEosEovLicence()
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);
@@ -424,12 +410,9 @@ bool LicenceELC11::createEosEovLicence()
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] = {};
@@ -456,7 +439,7 @@ bool LicenceELC11::createEosEovLicence()
FILE *fileLicence = fopen(licFileNameToSave, "wb");
if (fileLicence)
{
size_t r1 = fwrite(&totalEncryptedArray, sizeof(totalEncryptedArray), 1, fileLicence);
fwrite(&totalEncryptedArray, sizeof(totalEncryptedArray), 1, fileLicence);
// printf("License binary saved.\n");
fclose(fileLicence);
cout << licenseFileName << endl;
@@ -506,12 +489,10 @@ 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++)
for (unsigned int i = 0; i < dataFileName.length(); i++)
fileNameCh[i] = dataFileName[i];
cout << dataFileName << endl;
@@ -540,19 +521,14 @@ bool LicenceELC11::readEosEovLicence(string dataFileName)
}
fclose(licenceFile);
// this->cid = cid;
// this->csd = csd;
getSDData();
string licFileName = getLicenceName(licPostfix);
LicenceDataMainELC licenceHeader;
LicenceIdent licIdent;
LicenceData licEncryptedData;
LicenceDataMainELC licenceHeader{};
LicenceData licEncryptedData{};
memset(&licenceHeader, 0, sizeof(LicenceDataMainELC));
// memset(&licenceHeader, 0, sizeof(LicenceDataMainELC));
memcpy(&licenceHeader, licenceContent, sizeof(LicenceDataMainELC));
const int sizeOfEncryptedData = size - sizeof(LicenceDataMainELC);
@@ -560,20 +536,16 @@ bool LicenceELC11::readEosEovLicence(string dataFileName)
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
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);
@@ -584,7 +556,7 @@ bool LicenceELC11::readEosEovLicence(string dataFileName)
}
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)
@@ -602,7 +574,7 @@ bool LicenceELC11::readEosEovLicence(string dataFileName)
if (licType == PlcLicenceType::LicenceOther)
{
// TODO stará
// původní stará
}
else
{
@@ -657,22 +629,19 @@ bool LicenceELC11::readEosEovLicence(string dataFileName)
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);
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++)
for (unsigned 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++)
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;
BYTE licPostfix = 0;
FILE *licenceFile;
char ch;
long lSize;
size_t result;
const int fileNameLength = licFilePath.length();
char fileNameCh[fileNameLength] = {};
@@ -681,7 +650,8 @@ bool LicenceELC11::readLicence(LicenceInfoGeneral *licences)
licenceFile = fopen(fileNameCh, "rb"); // read mode
if (licenceFile == nullptr) throw LicenceException((int)Error11::LicenceReadError, "Licence read error: " + licFilePath);
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
@@ -703,13 +673,12 @@ bool LicenceELC11::readLicence(LicenceInfoGeneral *licences)
fclose(licenceFile);
getSDData();
//getSDData();?
LicenceDataMainELC licenceHeader;
LicenceIdent licIdent;
LicenceData licEncryptedData;
LicenceDataMainELC licenceHeader{};
LicenceData licEncryptedData{};
memset(&licenceHeader, 0, sizeof(LicenceDataMainELC));
// memset(&licenceHeader, 0, sizeof(LicenceDataMainELC));
memcpy(&licenceHeader, licenceContent, sizeof(LicenceDataMainELC));
const int sizeOfEncryptedData = size - sizeof(LicenceDataMainELC);
@@ -722,19 +691,13 @@ bool LicenceELC11::readLicence(LicenceInfoGeneral *licences)
{
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
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);
#ifdef DEB
cout << "sizeof(licEncryptedData: " << sizeof(licEncryptedData) << endl;
cout << "decrypted_len: " << decrypted_len << endl;
#endif
if (sizeof(licEncryptedData) != decrypted_len)
{
@@ -742,7 +705,7 @@ bool LicenceELC11::readLicence(LicenceInfoGeneral *licences)
}
else
{
memset(&licEncryptedData, 0, sizeof(licEncryptedData));
// 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)
@@ -782,22 +745,22 @@ bool LicenceELC11::readLicence(LicenceInfoGeneral *licences)
return true;
}
bool LicenceELC11::readLicence(string dataFileName, string licenceType, string licenceVersion, string cidArg, string csdArg)
{
// 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;
// for (unsigned int i = 0; i < cidArg.length(); i++)
// this->cid[i] = cidArg[i];
// for (unsigned 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);
}
// if (this->dataLicenceType == eoseovLicenceType)
// {
// return readEosEovLicence(dataFileName);
// }
return true;
}
// return true;
// }
LicenceELC11::~LicenceELC11() {}

View File

@@ -1,7 +1,5 @@
#include "licenceELC31.h"
#include "utils.h"
#include <map>
#include <vector>
LicenceELC31::LicenceELC31()
{
@@ -13,7 +11,7 @@ LicenceELC31::LicenceELC31(LicData &licData)
processInputConfiguration();
}
LicenceELC31::LicenceELC31(LicenceIdentification &licIdentification)
LicenceELC31::LicenceELC31(LicenceIdentification &licIdentification) : lIdentification(licIdentification)
{
}
@@ -24,16 +22,9 @@ bool LicenceELC31::processInputConfiguration()
int LicenceELC31::getDataPointsCount(int protocolId)
{
return 0;
return protocolId;
}
bool LicenceELC31::getLicenceInfo(int protocolId, void * ptr)
{
return true;
}
void LicenceELC31::createLicence()
{
}

View File

@@ -6,17 +6,6 @@
#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()
{
}
@@ -59,291 +48,6 @@ LicenceGenerator::LicenceGenerator(string uid, string cid, string csd, string da
}
}
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.cid_cdsPath = initStructure.cid_csd_filePath;
licence.licenceFilePath = initStructure.licenceFilePath;;
licence.readLicence(&this->licenceInfo);
break;
}
case 21:
{
LicenceELC21 licence = LicenceELC21(this->licIdentification);
this->licence21 = &licence;
licence.cid_cdsPath = initStructure.cid_csd_filePath;
licence.licenceFilePath = initStructure.licenceFilePath;;
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;
if (this->licenceInfo.licences.count(protocolId))
resultPtr->dataPointsCount = this->licenceInfo.licences.at(protocolId);
else
resultPtr->dataPointsCount = 0;
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;
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);
@@ -388,8 +92,8 @@ bool LicenceGenerator::processInputConfiguration()
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]);
//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]);
@@ -409,7 +113,7 @@ bool LicenceGenerator::processInputConfiguration()
void LicenceGenerator::createLicenceFile()
{
switch (licElcType)
switch (this->licIdentification.licElcType)
{
case ELCType::ELC1:
createLicenceELC1();
@@ -451,7 +155,7 @@ void LicenceGenerator::createLicenceELC1() // přejmenvat na ELC1
void LicenceGenerator::createLicenceELC2()
{
switch (licCompatibility)
switch (this->licIdentification.licCompatibility)
{
case 1:
LicenceELC21 licence = LicenceELC21(this->licData);
@@ -462,7 +166,7 @@ void LicenceGenerator::createLicenceELC2()
void LicenceGenerator::createLicenceELC3()
{
switch (licCompatibility)
switch (this->licIdentification.licCompatibility)
{
case 1:
LicenceELC31 licence = LicenceELC31(this->licData);

454
src/LicenceReader.cpp Normal file
View File

@@ -0,0 +1,454 @@
#include <licenceReader.h>
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
LicenceReader::LicenceReader()
{
}
// LicenceReader::LicenceReader(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;
// }
// }
// LicenceReader::LicenceReader(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 LicenceReader::initread(int elcType, InitStructure &initStructure)
{
try
{
elcSwitchType = elcType * 10 + licCompatibility;
if (init(elcType, initStructure))
{
switch (elcSwitchType)
{
case 11:
{ // old eoseov
LicenceELC11 licence = LicenceELC11(this->licIdentification);
this->licence11 = &licence;
licence.cid_cdsPath = initStructure.cid_csd_filePath;
licence.licenceFilePath = initStructure.licenceFilePath;;
this->licence11->readLicence(&this->licenceInfo);
break;
}
case 21:
{
LicenceELC21 licence = LicenceELC21(this->licIdentification);
this->licence21 = &licence;
licence.cid_cdsPath = initStructure.cid_csd_filePath;
licence.licenceFilePath = initStructure.licenceFilePath;;
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 LicenceReader::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 LicenceReader::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 LicenceReader::init(int elcType, InitStructure &initStructure)
{
try
{
if (elcType > 3)
{
error.code = (int)GeneralError::ELCNotImplemented;
error.message = "ELC není implementováno.";
throw LicenceException((int)GeneralError::ELCNotImplemented, error.message);
}
this->licIdentification.licElcType = (ELCType)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 = elcType * 10 + licCompatibility;
return true; // TODO testy
}
// bool LicenceReader::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
// }
bool LicenceReader::getLicenceItemInfo(int protocolId, void *returnItemStructure)
{
try
{
switch (elcSwitchType)
{
case 11:
{ // old eoseov
LicenceItem11 *resultPtr = static_cast<LicenceItem11 *>(returnItemStructure);
resultPtr->protocolId = protocolId;
if (this->licenceInfo.licences.count(protocolId))
resultPtr->dataPointsCount = this->licenceInfo.licences.at(protocolId);
else
resultPtr->dataPointsCount = 0;
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;
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 LicenceReader::getLicenceInfo(void *returnStructure)
{
// 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(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(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 LicenceReader::processInputConfiguration()
// {
// string fullFile = getCompletePath(this->configFileName);
// const size_t 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 LicenceReader::readLicenceFile()
{
switch (this->licIdentification.licElcType)
{
case ELCType::ELC1:
readLicenceELC1();
break;
case ELCType::ELC2:
readLicenceELC2();
break;
case ELCType::ELC3:
readLicenceELC3();
break;
}
}
void LicenceReader::readLicenceELC1()
{
cout << "reading ELC1" << endl;
}
void LicenceReader::readLicenceELC2()
{
LicenceELC21 licence = LicenceELC21(this->licIdentification);
}
void LicenceReader::readLicenceELC3()
{
cout << "reading ELC3" << endl;
}
LicenceReader::~LicenceReader()
{
}

View File

@@ -1,107 +0,0 @@
#define NEW =1
#ifdef NEW
#include <stdio.h>
#include "utils.h"
#include "licenceGenerator.h"
#include "licenceCommon.h"
#define FILEBUFFER 300
#define TWO_HOURSE_SECONDS 7200
/// @brief hlavní funkce
/// @param argc
/// @param argv parametry pro generování licence
/// @return
int main5(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;
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 = "test";
initStructure.cid_csd_filePath = "test";
// 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 0;
}
#endif
#ifndef NEW
#include <stdio.h>
#include "utils.h"
#include "plcLicence.h"
// #include "licenceGenerator.h"
// #include "licenceCommon.h"
#define FILEBUFFER 300
#define TWO_HOURSE_SECONDS 7200
/// @brief hlavní funkce
/// @param argc
/// @param argv parametry pro generování licence
/// @return
int main(int argc, char *argv[])
{
unordered_map<string, string> arguments = getArguments(argc, argv);
PlcLicence plcWriteLicence = PlcLicence(arguments["-cid"], arguments["-csd"], arguments["-outputType"], arguments["-configFileName"]);
if (plcWriteLicence.CreateLicence() == false)
{
cerr << "Licence creation failed";
}
// cout << "Reading Test" << endl;
system("pause");
return 0;
}
#endif

View File

@@ -1,634 +0,0 @@
#include <cstring>
#include <fstream>
#include <filesystem>
#include "plcLicence.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_IDTypeStrData[] = {"neznamo", "DDTS", "EOV-OSV", "DRT"};
const BYTE cnibblescount = 32;
std::string cSDMonthStr[] = {"-", "I.", "II.", "III.", "IV.", "V.", "VI.", "VII.", "VIII.", "IX.", "X.", "XI.", "XII.", "-", "-", "-"};
BYTE cHexNibble_to_No[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 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};
std::string cEzLic_p78ou3_CipherAES = "aes-256-cbc"; // konfigurace kriptovaciho algoritmu
const string eoseovLicenceType = "EOV_OSV";
//enum LicenceType { EovOsv = 1 };
PlcLicence::PlcLicence()
{
}
PlcLicence::PlcLicence(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 PlcLicence::processConfigFile(string &dataFileName)
{
string fullFile = getCompletePath(dataFileName);
const int fileNameLength = fullFile.length();
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)
{
this->stationName = doc.child("data").child("station").child_value();
this->distributor = doc.child("data").child("distributor").child_value();
this->dataLicenceType = doc.child("data").child("licenceType").child_value();
this->dataLicenceVersion = doc.child("data").child("licenceType").attribute("version").value();
this->dataGenerationType = this->dataLicenceVersion;
this->dataCryptoVersion = this->dataLicenceVersion;
// if (licType == "EOV_OSV") this->licType = cEzLic_p78ou3_IDType_EOVOSV;// 1;
// cout << doc.child("data").child("plcType").attribute("t").value() << endl; //přiklad pro atributy
}
else
{
std::cerr << "Unable to open the file." << std::endl;
}
}
/// @brief reads data from CID a CSD
void PlcLicence::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_No[this->sdData.CID_nibble[2 * i]] << 4 | cHexNibble_to_No[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_No[this->sdData.CID[16]];
this->sdData.productRevision_sw = cHexNibble_to_No[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_No[this->sdData.CID_nibble[27]] * 10 + cHexNibble_to_No[this->sdData.CID_nibble[28]] + 2000;
this->sdData.manufacturerDate_month = cHexNibble_to_No[this->sdData.CID_nibble[29]];
string date = cSDMonthStr[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_No[this->sdData.CSD_nibble[2 * i]] << 4 | cHexNibble_to_No[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 PlcLicence::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);
}
}
/// @brief get proper licencename
/// @param licPostfix
/// @return
string PlcLicence::getLicenceName(BYTE licPostfix)
{
string result = "";
char prefixChar = 97;
if (licPostfix > 9) // chyba
{
}
if (licType == LicenceType::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 PlcLicence::CreateLicence()
{
if (this->dataLicenceType == eoseovLicenceType)
{
return CreateEosEovLicence();
}
else
{
return false;
}
}
bool PlcLicence::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)LicenceType::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;
cout << "cardSize: " << this->sdData.cardSize << endl;
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();
cout << "date:" << dataToFile.header.licDate << endl;
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;
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));
cout << endl;
for (auto x : byteArray) cout << (int)x << "-";
cout << endl;
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)
{
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 the file." << std::endl;
}
return true;
}
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 PlcLicence::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 == NULL)
{
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 == LicenceType::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 PlcLicence::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;
}

94
src/ReadLicence.cpp Normal file
View File

@@ -0,0 +1,94 @@
#include <stdio.h>
#include "utils.h"
#include "licenceGenerator.h"
#include "licenceReader.h"
#include "licenceCommon.h"
/// @brief hlavní funkce
/// @param argc
/// @param argv parametry pro generování licence
/// @return
int main()
{
// unordered_map<string, string> arguments = getArguments(argc, argv);
// try
// {
// unordered_map<string, string> arguments = getArguments(argc, argv);
// LicenceGenerator generatorOld = LicenceGenerator(arguments["-uid"], arguments["-cid"], arguments["-csd"], arguments["-configFileName"]);
// generatorOld.createLicenceFile();
// system("pause");
// return SUCCES;
// }
// catch (...)
// {
// cerr << "Obecná chyba\n";
// }
// system("pause");
// return SUCCES;
try
{
int protocolId = 222;
LicenceReader licenceReader1 {};
InitStructure initStructure;
initStructure.licenceType = (int)LicenceType::EOS_EOV;
initStructure.licenceVersion = 1;
initStructure.licenceIndex = 0;
initStructure.compatibility = 1;
initStructure.licenceFilePath = "";
initStructure.cid_csd_filePath = "";
cout << "-- verze #1: init a iterace" << "\n";
//verze #1: načtení kompletní licence a zobrazení
if (licenceReader1.init(2, initStructure))
{
LicenceInfo21 info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
if (licenceReader1.getLicenceInfo(&info))
{
std::cout << "Počet licenčních bodů pro : " << protocolId << ": " << info.reqDataPointsCount << std::endl;
if (info.licences.count(protocolId) > 0) cout << "Počet z vectoru pro : " << protocolId << ": " << info.licences.at(protocolId) << 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ě: " << licenceReader1.error.message;
}
else
{
cerr << "Došlo k chybě: " << licenceReader1.error.message;
}
cout << "\n" << "-- verze #2: init a iterace" << "\n";
//verze #2 : iterace pro kazdý bod zvlášť
LicenceReader licenceReader2 {};
if (licenceReader2.initread(2, initStructure))
{
LicenceItem21 info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
if (licenceReader2.getLicenceItemInfo(protocolId, &info))
{
std::cout << "Počet licenčních bodů pro " << info.protocolId << ": " << info.dataPointsCount << std::endl;
}
else
cerr << "Došlo k chybě: " << licenceReader2.error.message;
}
else
{
cerr << "Došlo k chybě: " << licenceReader2.error.message;
}
}
catch (...)
{
cerr << "Obecná chyba\n";
}
system("pause");
return SUCCES;
}

View File

@@ -1,8 +1,5 @@
#include "utils.h"
#include "SDCard.h"
#include <map>
#include <vector>
#include <fstream>
SDCard::SDCard()
{
@@ -11,17 +8,15 @@ SDCard::SDCard()
SDCard::SDCard(const string cds_cid_Path)
{
this->filePath = cds_cid_Path;
getCIDFromFile();
getCSDFromFile();
if (getCIDFromFile() == false) return;
if (getCSDFromFile() == false) return;
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];
for (unsigned int i = 0; i < cid.length(); i++) this->cid[i] = cid[i];
for (unsigned int i = 0; i < csd.length(); i++) this->csd[i] = csd[i];
this->isLoaded = SDCard::readSDCard();
}
@@ -73,11 +68,6 @@ bool SDCard::readSDCard()
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];
@@ -93,24 +83,53 @@ bool SDCard::readSDCard()
this->cardData.cardGSize = (this->cardData.cardSize + 1) / 2048;
}
return true;
BYTE sdCrc = 0;
for (int i = 0; i <= 14; i++)
{
BYTE sdChar = this->cardData.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->cardData.CRCOK = ((sdCrc << 1) | 1) == this->cardData.CID[15];
this->cardData.crcCorrect = (int)this->cardData.CID[15] == (int)((sdCrc << 1) | 1);
return this->cardData.crcCorrect;
}
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];
vector<char> content;
if (readFile(this->filePath + "cid", content) == false)
{
return false;
}
if (content.size() >= 32)
{
for (int i = 0; i<32;i++) this->cid[i] = content[i];
}
else return false;
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];
vector<char> content;
if (readFile(this->filePath + "csd", content) == false)
{
return false;
}
if (content.size() >= 32)
{
for (int i = 0; i<32;i++) this->csd[i] = content[i];
}
else return false;
return true;
}

View File

@@ -18,6 +18,7 @@ The definition of count_x() assumes that the char is a C-style string, that i
points to a zero-terminated array of char.
In older code, 0 or NULL is typically used instead of nullptr (§7.2.2). However, using nullptr
eliminates potential confusion between integers (such as 0 or NULL) and pointers (such as nullptr).
--------------------------------------------------------------------------------------------------
void f(Vector v, Vector& rv, Vector pv)
{
@@ -25,6 +26,7 @@ int i1 = v.sz; // access through name
int i2 = rv.sz; // access through reference
int i4 = pv>sz; // access through pointer
}
--------------------------------------------------------------------------------------------------
class complex {
double re, im; // representation: two doubles
@@ -33,5 +35,69 @@ complex(double r, double i) :re{r}, im{i} {}
............
complex a {2.3}; // construct {2.3,0.0} from 2.3
--------------------------------------------------------------------------------------------------
Vector::Vector(std::initializ er_list<double> lst) // initialize with a list
:elem{new double[lst.siz e()]}, sz{lst.siz e()}
{
copy(lst.begin(),lst.end(),elem); // copy from lst into elem
}
--------------------------------------------------------------------------------------------------
class Container {
public:
virtual double& operator[](int) = 0; // pure virtual function - MUST be implemnted
virtual int size() const = 0; // const member function (§3.2.1.1)
virtual ˜Container() {} // destructor (§3.2.1.2)
};
-------------------------------- move konstruktor -------------------------------------------------
the result out of a function: we wanted to move a Vector rather than to copy it. Fortunately, we can
state that intent:
class Vector {
// ...
Vector(const Vector& a); // copy constr uctor
Vector& operator=(const Vector& a); // copy assignment
Vector(Vector&& a); // move constr uctor
Vector& operator=(Vector&& a); // move assignment
};
Given that definition, the compiler will choose the move constructor to implement the transfer of
the return value out of the function. This means that r=x+y+z will involve no copying of Vectors.
Instead, Vectors are just moved.
As is typical, Vectors move constructor is trivial to define:
Vector::Vector(Vector&& a)
:elem{a.elem}, // "grab the elements" from a
sz{a.sz}
{
a.elem = nullptr; // now a has no elements
a.sz = 0;
}
The && means rvalue reference and is a reference to which we can bind an rvalue (§6.4.1). The
word rvalue is intended to complement lvalue, which roughly means something that can
appear on the left-hand side of an assignment. So an rvalue is to a first approximation a value
that you cant assign to, such as an integer returned by a function call, and an rvalue reference is a
reference to something that nobody else can assign to. The res local variable in operator+() for Vectors is an example.
A move constructor does not take a const argument: after all, a move constructor is supposed to
remove the value from its argument. A move assignment is defined similarly.
A move operation is applied when an rvalue reference is used as an initializer or as the righthand side of an assignment.
schema:
- http://127.0.0.1:24100/hasura/v1/graphql:
headers:
x-hasura-admin-secret: loutak
documents: 'src/**/*.graphql'
generates:
./src/types-graphql.d.ts:
plugins:
- typescript
- typescript-operations
PUBLIC_URL="https://sprava.app.elzel.cz/"
GENERATE_SOURCEMAP=true
REACT_APP_TITLE="Správa projektů"
REACT_APP_HASURA_URL="http://127.0.0.1:40010/v1/graphql"
REACT_APP_PUBLIC_URL="https://sprava.app.elzel.cz/"
REACT_APP_VERSION=$npm_package_version
REACT_APP_NAME=$npm_package_name
DISABLE_ESLINT_PLUGIN=true

0
src/_notestest.cpp Normal file
View File

View File

@@ -1,11 +1,6 @@
#include "licenceELC21.h"
#include "utils.h"
#include "SDCard.h"
#include <unordered_map>
#include <vector>
#include <limits>
#include <fstream>
LicenceELC21::LicenceELC21()
{
@@ -14,21 +9,16 @@ LicenceELC21::LicenceELC21()
LicenceELC21::LicenceELC21(LicenceIdentification &licIdentification, LicData &licData)
: lIdentification(licIdentification), lData(licData)
{
// lIdentification = licIdentification;
// lData = licData;
}
LicenceELC21::LicenceELC21(LicenceIdentification &licIdentification)
: lIdentification(licIdentification)
LicenceELC21::LicenceELC21(LicenceIdentification &licIdentification): lIdentification(licIdentification)
{
// lIdentification = licIdentification;
}
LicenceELC21::LicenceELC21(LicData &licData)
: lData(licData)
LicenceELC21::LicenceELC21(LicData &licData): lData(licData)
{
// lData = licData;
processInputConfiguration();
if (processInputConfiguration() == false) throw LicenceException((int)Error21::LicenceReadError, "Chyba při čtení licence");
}
bool LicenceELC21::createLicence()
@@ -44,9 +34,9 @@ bool LicenceELC21::createLicence()
this->licBody.licenceIdentHeader.licItemCount = this->licBody.privateContent.dataItems.size();
this->licBody.licenceIdentHeader.publicHeaderLength = this->licBody.publicHeader.length();
vector<unsigned char> publicContent(1000);
vector<unsigned char> privateContent(1000);
vector<unsigned char> privateContentEncrypted(1000);
vector<unsigned char> publicContent;
vector<unsigned char> privateContent;
vector<unsigned char> privateContentEncrypted;
publicContent.push_back(this->licBody.licId.licIdent[0]);
@@ -68,13 +58,6 @@ bool LicenceELC21::createLicence()
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);
@@ -105,7 +88,7 @@ bool LicenceELC21::createLicence()
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++)
for (unsigned int i = 0; i < sizeof(dataItem.dummy); i++)
privateContent.push_back(i);
}
@@ -116,33 +99,8 @@ bool LicenceELC21::createLicence()
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);
@@ -159,7 +117,6 @@ bool LicenceELC21::createLicence()
outputFile.close();
cout << licfileName;
return true;
}
@@ -172,8 +129,8 @@ bool LicenceELC21::readLicence(LicenceInfoGeneral * licences)
string licFileName = getLicenceName();
string licFilePath = this->licenceFilePath+licFileName;
cout << licFilePath;
// Create an unsigned char vector to store the file data
vector<char> content;
if (readFile(licFilePath, content) == false)
{
@@ -195,19 +152,7 @@ bool LicenceELC21::readLicence(LicenceInfoGeneral * licences)
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
//~~~uint16_t crcPublic = bytesToWord(content[18 + licBody.licenceIdentHeader.publicHeaderLength], content[19 + licBody.licenceIdentHeader.publicHeaderLength]);
int elcVersion = (int)licBody.licId.licIdent[3] - 48;
@@ -218,26 +163,9 @@ bool LicenceELC21::readLicence(LicenceInfoGeneral * licences)
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];
@@ -248,7 +176,7 @@ bool LicenceELC21::readLicence(LicenceInfoGeneral * licences)
licBodyDecrypted.licenceIdentHeader.cardSize = bytesToWord(privateContentDecrypted[7], privateContentDecrypted[8]);
licBodyDecrypted.licenceIdentHeader.serialNumber = bytesToDword(privateContentDecrypted[9], privateContentDecrypted[10], privateContentDecrypted[11], privateContentDecrypted[12]);
//TODO testy na CRC
//~~~CRC
if (licBodyDecrypted.licenceIdentHeader.licItemCount != this->licBody.licenceIdentHeader.licItemCount)
{
@@ -294,8 +222,8 @@ bool LicenceELC21::processInputConfiguration()
}
else
{
cerr << endl
<< " ERROR MISSING licenceType " << endl;
errorMessage.code = (int)Error21::LicenceMismatch;
errorMessage.message = "ERROR MISSING licenceType";
return false;
}
@@ -334,10 +262,6 @@ void LicenceELC21::getLicenceItems()
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());
@@ -388,7 +312,7 @@ void LicenceELC21::getHeader()
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("\",");
@@ -404,10 +328,7 @@ void LicenceELC21::getHeader()
licBody.publicHeader.append("\"items\":[");
for (pugi::xml_node tool : lData.doc->child("licence").child("items"))
{
lIdentification.licItemsCount++;
}
lIdentification.licItemsCount = std::distance(lData.doc->child("licence").child("items").begin(), lData.doc->child("licence").child("items").end());
int nodeIndex = 0;
int itemIndex = 0;
@@ -451,8 +372,8 @@ void LicenceELC21::getHeader()
vector<unsigned char> LicenceELC21::cryptPrivateContent(const std::vector<unsigned char> &content)
{
BYTE initVector[15] = {0};
BYTE aesKey[32] = {0};
BYTE initVector[15] = {};
BYTE aesKey[32] = {};
LicenceELC21::initVector(initVector, aesKey);
@@ -460,7 +381,8 @@ vector<unsigned char> LicenceELC21::cryptPrivateContent(const std::vector<unsign
const unsigned char *plainTextArray = content.data();
int finalEncryptedLength = encrypt(plainTextArray, content.size(), aesKey, initVector, encrypted);
std::size_t charArraySize = sizeof(encrypted) / sizeof(unsigned char);
if (finalEncryptedLength <= 0) throw LicenceException((int)GeneralError::EncryptError, "Chyba při kryptování.");
std::vector<unsigned char> result(encrypted, encrypted + finalEncryptedLength);
return result;
@@ -478,8 +400,8 @@ vector<unsigned char> LicenceELC21::decryptPrivateContent(const std::vector<unsi
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::size_t charArraySize = sizeof(decrypted) / sizeof(unsigned char);
std::vector<unsigned char> result(decrypted, decrypted + decrypted_len);
return result;
@@ -563,7 +485,6 @@ void LicenceELC21::initVector(BYTE (&iVector)[], BYTE (&key)[])
/// @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;
@@ -582,7 +503,7 @@ string LicenceELC21::getLicenceName()
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};
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));
@@ -641,7 +562,7 @@ bool LicenceELC21::getLicenceItemInfo(int protocolId, void *returnItemStructure)
return true;
}
bool LicenceELC21::getLicenceInfo(int protocolId, void *returnStructure)
bool LicenceELC21::getLicenceInfo(void *returnStructure)
{
if (returnStructure != nullptr)
{
@@ -649,7 +570,6 @@ bool LicenceELC21::getLicenceInfo(int protocolId, void *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

View File

@@ -1,3 +1,7 @@
TODO: ¨
// original jsou testy na velikost přečteného file, zatím TODO 549-LicenceELC11
-0
-255
-255

View File

@@ -1,28 +1,9 @@
#include <stdint.h>
#include <vector>
#include <wchar.h>
#include <cstring>
#include <ctime>
#include <chrono>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <codecvt>
#include <unordered_map>
#include <format>
// #include <openssl/evp.h>
// #include <openssl/aes.h>
#include <openssl/conf.h>
#include <openssl/err.h> /* errors */
#include <openssl/ssl.h> /* core library */
// #include <openssl/sha.h>
#include "utils.h"
using namespace std;
const std::string base64_chars =
@@ -35,48 +16,9 @@ const char base64_url_alphabet[] = {
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'};
void TestFunction(int i)
void getCharsFromString(string &source, char *charArray, size_t length)
{
std::cout << i << "\n";
std::cout << i + 1 << "\n";
}
void generatePause()
{
cin.get();
// system("pause");
}
string getXmlContentFromString(string source, string xmlTag)
{
int xmlTagSize = xmlTag.length();
int keyIndexStart = source.find("<" + xmlTag + ">");
int keyIndexEnd = source.find("</" + xmlTag + ">");
std::string keyContentString = source.substr(keyIndexStart + xmlTagSize + 2, (keyIndexEnd - keyIndexStart - xmlTagSize - 2));
return keyContentString;
}
string getString(unsigned char *charArray)
{
std::string fileContent(reinterpret_cast<char *>(charArray), sizeof(charArray));
return fileContent;
}
void getCharsFromString1(string source, char *charArray)
{
memset(charArray, 0, sizeof(charArray));
int length = source.length(); // Length of the string (excluding null character)
// charArray[length]; // Character array to store the string
for (int i = 0; i < length; i++)
{
charArray[i] = source[i];
}
}
void getCharsFromString(string &source, char *charArray, int length)
{
memset(charArray, 0, length);
for (int i = 0; i < length; i++)
for (size_t i = 0; i < length; i++)
{
charArray[i] = source[i];
}
@@ -84,44 +26,13 @@ void getCharsFromString(string &source, char *charArray, int length)
void getCharsFromString(string source, char *charArray)
{
memset(charArray, 0, sizeof(charArray));
int length = source.length(); // Length of the string (excluding null character)
// charArray[length]; // Character array to store the string
for (int i = 0; i < length; i++)
size_t length = source.length();
for (size_t i = 0; i < length; i++)
{
charArray[i] = source[i];
}
}
float byteArrayToFloat(const BYTE *byteArray)
{
// Ensure that the byte array has at least 4 elements (32 bits)
if (byteArray == NULL)
{
// Handle error: The pointer is NULL
return 0.0f; // or any appropriate error handling
}
int sizeArray = sizeof(byteArray);
// Interpret the byte array as a 32-bit floating-point value
uint32_t intValue = 0;
if (sizeArray > 0)
intValue |= ((uint32_t)byteArray[0] << 24);
if (sizeArray > 1)
intValue |= ((uint32_t)byteArray[1] << 16);
if (sizeArray > 2)
intValue |= ((uint32_t)byteArray[2] << 8);
if (sizeArray > 0)
intValue |= byteArray[3];
// Typecast the integer representation to a float
float floatValue;
memcpy(&floatValue, &intValue, sizeof(float));
return floatValue;
}
std::string right(const std::string &sourceString, size_t numChars)
{
if (numChars >= sourceString.size())
@@ -131,72 +42,6 @@ std::string right(const std::string &sourceString, size_t numChars)
return sourceString.substr(sourceString.size() - numChars);
}
std::tm dt_to_date(const std::chrono::system_clock::time_point &tp)
{
std::time_t time = std::chrono::system_clock::to_time_t(tp);
return *std::localtime(&time);
}
std::string parseCID(const std::string &cidHex)
{
// Convert hexadecimal string to binary string
std::string cidBinary;
for (char c : cidHex)
{
std::string binary = "0000";
int val;
if (c >= '0' && c <= '9')
{
val = c - '0';
}
else if (c >= 'a' && c <= 'f')
{
val = c - 'a' + 10;
}
else if (c >= 'A' && c <= 'F')
{
val = c - 'A' + 10;
}
else
{
continue; // Ignore non-hex characters
}
for (int i = 3; i >= 0; --i)
{
binary[i] = '0' + (val & 1);
val >>= 1;
}
cidBinary += binary;
}
// Define the length of individual fields in the CID
const int lengths[] = {8, 16, 40, 8, 32, 12, 7, 4};
const char *fields[] = {"MID", "OID", "PNM", "PRV", "PSN", "MDT", "CRC", "unused"};
// Parse the binary string and print individual fields
int pos = 0;
for (int i = 0; i < 8; ++i)
{
std::string fieldData = cidBinary.substr(pos, lengths[i]);
std::cout << fields[i] << ": " << fieldData << std::endl;
pos += lengths[i];
}
return cidBinary; // Optionally, you can return the full binary string
}
void bitsToCharArray(const std::string &bitsStr, char *charArray)
{
int bitsLen = bitsStr.length();
int charArraySize = bitsLen / 8; // Assuming bitsStr.length() is a multiple of 8
for (int i = 0; i < charArraySize; i++)
{
std::string byteStr = bitsStr.substr(i * 8, 8);
charArray[i] = std::bitset<8>(byteStr).to_ulong();
}
}
uint16_t calculateCRC16(const uint8_t *data, size_t length)
{
const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
@@ -236,155 +81,6 @@ uint16_t crc16(const unsigned char *data_p, unsigned char length)
return crc;
}
void wordToByteArray(uint16_t wordValue, uint8_t byteArray[2])
{
byteArray[0] = static_cast<uint8_t>(wordValue & 0xFF); // Low byte
byteArray[1] = static_cast<uint8_t>((wordValue >> 8) & 0xFF); // High byte
}
uint16_t calculateCrc(const uint8_t *data, size_t length)
{
uint16_t crc = 0xFFFF;
uint16_t makeData = 0;
uint16_t cCrcTable[] = {0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040};
uint8_t byteArray[2];
for (int i = 0; i < length; i++)
{
// wordToByteArray(crc, byteArray);
makeData = data[i] ^ (crc);
crc = crc >> 8;
crc = crc ^ cCrcTable[i];
data = data + 1;
}
/* orig
crc := 16#FFFF;
FOR i := 0 TO dataLen - 1 DO
makeData := data^ XOR WORD_TO_BYTE( crc );
crc := SHR( crc, 8 );
crc := crc XOR cCrcTable[makeData];
data := data + 1;
END_FOR;
fEz_crc16 := crc;
*/
return crc;
}
void showCurrentTime()
{
std::time_t now = std::time(nullptr);
std::cout << "Current time (ctime): " << std::ctime(&now);
// Using chrono to get the current time
auto currentTime = std::chrono::system_clock::now();
std::time_t currentTimeT = std::chrono::system_clock::to_time_t(currentTime);
std::cout << "Current time (chrono): " << std::ctime(&currentTimeT);
}
WORD getCurrentDateAsCODESYSDate()
{
/*
Bits 0-4: Day (1 to 31)
Bits 5-8: Month (1 to 12)
Bits 9-15: Year (0 to 127, where 0 represents the year 1984)
date: 2023-07-21 = 0x0A17 ?
daatum: 060: 80 F9 C6 64
*/
std::time_t currentTime = std::time(nullptr);
std::tm *currentTm = std::localtime(&currentTime);
int year = currentTm->tm_year + 1900; // tm_year represents years since 1900
int month = currentTm->tm_mon + 1; // tm_mon represents months from 0 to 11
int day = currentTm->tm_mday;
uint16_t codesysDate = (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);
return codesysDate;
}
DWORD getCurrentDateAsCODESYSDateDword()
{
std::time_t currentTime = std::time(nullptr);
std::tm *currentTm = std::localtime(&currentTime);
int year = currentTm->tm_year + 1900; // tm_year represents years since 1900
int month = currentTm->tm_mon + 1; // tm_mon represents months from 0 to 11
int day = currentTm->tm_mday;
DWORD codesysDate = (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);
return codesysDate;
}
uint16_t convertToCODESYSDate(int day, int month, int year)
{
return (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);
}
uint16_t convertToCODESYSTime(int hour, int minute)
{
return (static_cast<uint16_t>(hour) << 11) | (static_cast<uint16_t>(minute) << 5);
}
DateAndTime getCurrentDateTimeAsCODESYSDateTime()
{
std::time_t currentTime = std::time(nullptr);
std::tm *currentTm = std::localtime(&currentTime);
int year = currentTm->tm_year + 1900; // tm_year represents years since 1900
int month = currentTm->tm_mon + 1; // tm_mon represents months from 0 to 11
int day = currentTm->tm_mday;
int hour = currentTm->tm_hour;
int minute = currentTm->tm_min;
int second = currentTm->tm_sec;
uint16_t codesysDate = (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);
uint16_t codesysTime = (static_cast<uint16_t>(hour) << 11) | (static_cast<uint16_t>(minute) << 5) | (static_cast<uint16_t>(second) >> 1);
DateAndTime codesysDateTime = {codesysDate, codesysTime};
return codesysDateTime;
}
DATE getLicDate()
{
time_t ttime = time(0);
@@ -411,37 +107,6 @@ string getDate()
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;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key.data(), iv.data());
int ciphertext_len;
int len;
int max_chunk_size = EVP_CIPHER_block_size(EVP_aes_256_cbc());
ciphertext.resize(plaintext.size() + max_chunk_size);
EVP_EncryptUpdate(ctx, ciphertext.data(), &len, plaintext.data(), plaintext.size());
ciphertext_len = len;
EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len);
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
ciphertext.resize(ciphertext_len);
return ciphertext;
}
void handleErrors(void)
{
ERR_print_errors_fp(stderr);
abort();
}
int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext)
{
@@ -452,8 +117,8 @@ int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *ke
int ciphertext_len;
/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new()))
handleErrors();
if (!(ctx = EVP_CIPHER_CTX_new())) return -1;
/*
* Initialise the encryption operation. IMPORTANT - ensure you use a key
@@ -463,14 +128,14 @@ int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *ke
* is 128 bits
*/
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
return -1;
/*
* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
return -1;
ciphertext_len = len;
/*
@@ -478,7 +143,7 @@ int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *ke
* this stage.
*/
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
handleErrors();
return -1;
ciphertext_len += len;
/* Clean up */
@@ -498,7 +163,7 @@ int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *
/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new()))
handleErrors();
return -1;
/*
* Initialise the decryption operation. IMPORTANT - ensure you use a key
@@ -508,14 +173,14 @@ int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *
* is 128 bits
*/
if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
return -1;
/*
* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary.
*/
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
return -1;
plaintext_len = len;
/*
@@ -523,7 +188,8 @@ int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *
* this stage.
*/
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
handleErrors();
return -1;
plaintext_len += len;
/* Clean up */
@@ -532,54 +198,6 @@ int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *
return plaintext_len;
}
bool CompareFiles(const char *fileName, const char *fileName1)
{
FILE *fp1;
FILE *fp2;
fp1 = fopen(fileName, "rb"); // read mode
fseek(fp1, 0, SEEK_END); // seek to end of file
int size1 = ftell(fp1); // get current file pointer
fseek(fp1, 0, SEEK_SET);
fp2 = fopen(fileName1, "rb"); // read mode
fseek(fp2, 0, SEEK_END); // seek to end of file
int size2 = ftell(fp2); // get current file pointer
fseek(fp2, 0, SEEK_SET);
if (fp1 == NULL || fp2 == NULL)
{
while (1)
{
int byte1 = fgetc(fp1);
int byte2 = fgetc(fp2);
if (byte1 == EOF || byte2 == EOF)
{
if (byte1 != byte2)
{
return false; // 1 indicates files are different
}
break;
}
if (byte1 != byte2)
{
return false; // 1 indicates files are different
break;
}
}
}
else
return false;
fclose(fp1);
fclose(fp2);
return true;
}
// converts character array
// to string and returns it
string convertToString(char *a, int size)
@@ -618,87 +236,6 @@ std::string base64_decode(const std::string &in)
return out;
}
void processCharArray(const unsigned char *arr)
{
size_t arraySize = sizeof(arr) / sizeof(arr[0]);
for (size_t i = 0; i < arraySize; ++i)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
std::string base64_encode(const std::string &in)
{
std::string out;
int val = 0, valb = -6;
size_t len = in.length();
unsigned int i = 0;
for (i = 0; i < len; i++)
{
unsigned char c = in[i];
val = (val << 8) + c;
valb += 8;
while (valb >= 0)
{
out.push_back(base64_url_alphabet[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6)
{
out.push_back(base64_url_alphabet[((val << 8) >> (valb + 8)) & 0x3F]);
}
return out;
}
std::string base64_encode_array(const unsigned char *source)
{
size_t arraySize = sizeof(source) / sizeof(source[0]);
std::string out;
int val = 0, valb = -6;
unsigned int i = 0;
for (i = 0; i < arraySize; i++)
{
unsigned char c = source[i];
val = (val << 8) + c;
valb += 8;
while (valb >= 0)
{
out.push_back(base64_url_alphabet[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6)
{
out.push_back(base64_url_alphabet[((val << 8) >> (valb + 8)) & 0x3F]);
}
return out;
}
std::string base64_decode_ai(const std::string &encoded)
{
std::string decoded;
int val = 0, valb = -8;
for (char c : encoded)
{
if (base64_chars.find(c) == std::string::npos)
break;
val = (val << 6) + base64_chars.find(c);
valb += 6;
if (valb >= 0)
{
decoded.push_back(static_cast<unsigned char>((val >> valb) & 0xFF));
valb -= 8;
}
}
return decoded;
}
std::string base64_encode_ai(const std::string &input)
{
std::string encoded;
@@ -774,114 +311,34 @@ unordered_map<string, string> getArguments(int argc, char *argv[])
return result;
}
unordered_map<string, const char *> mapArguments(int argc, char *argv[])
{
const char splitChar = '=';
unordered_map<string, const char *> result;
if (argc <= 1)
return result;
for (int i = 1; i < argc; ++i)
{
bool isArgName = true;
int argLength = strlen(argv[i]);
string argName;
string argValue;
char *argValueChar;
for (int j = 0; j < argLength; j++)
{
if (argv[i][j] == splitChar)
{
isArgName = false;
continue;
}
if (isArgName)
{
argName += argv[i][j];
}
else
{
argValue += argv[i][j];
}
}
const char *chValue = argValue.c_str();
result.insert(make_pair(argName, chValue));
}
return result;
}
string getCompletePath(string fileName)
{
#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 fullPathStrOther = fullPathOther.string();
return fullPathStrOther;
//warning TODO filesystem
char path[PATH_MAX+1] = {};
ssize_t length = readlink("/proc/self/exe", path, PATH_MAX);
path[length] = '\0';
string result = string(dirname(path)) + "/" + fileName;
return result;
//return std::string( result, (count > 0) ? count : 0 );
// 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 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
@@ -930,33 +387,6 @@ std::vector<unsigned char> joinVectors(const std::vector<unsigned char> &vector1
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);
@@ -975,16 +405,5 @@ bool readFile(string fileName, vector<char> &output)
file.close();
// 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;
}