Compare commits

...

37 Commits

Author SHA1 Message Date
a5139db75a uprava 2024-10-03 11:57:02 +02:00
e21828d63f oprava directiv 2024-10-03 11:47:51 +02:00
4dcd40aadf oprava #define direktiv 2024-10-03 11:44:03 +02:00
a4e66ddaaf Tag 2024-06-24 08:46:25 +02:00
122f5cb92b Publikační verze 1 2024-06-24 08:43:36 +02:00
e157f5cc39 readme 2024-06-05 08:10:34 +02:00
b3178445c3 verzování 2024-06-04 12:48:42 +02:00
d827ccf34f ELC 3 2024-05-16 11:42:46 +02:00
d03261b873 ELC 3 2024-05-16 09:25:25 +02:00
ca93b3369f ELC 3 2024-05-14 14:51:30 +02:00
63d8178b4b upravy 2024-04-15 09:32:46 +02:00
e4b7cb5fb7 piřdání cesty k informaci o licenci 2024-04-15 09:24:32 +02:00
70e1fd9c4d Git čistka 2024-04-12 12:20:27 +02:00
671a764b04 Oddělení informace o licenci 2024-04-12 12:15:37 +02:00
2b7a68e64a upravy, čištení 2024-04-12 10:26:31 +02:00
3b1ee6038e Upravy a opravování kryptování 2024-04-11 14:31:24 +02:00
ead3ba6e3e upravy opravy 2024-04-10 08:03:43 +02:00
79cc4998bc Upravy popisků 2024-04-03 09:38:01 +02:00
2175852bc0 testování filip 2024-03-28 14:17:49 +01:00
22a97056f9 Upravy z testování Filip 2024-03-12 09:46:24 +01:00
2bfc662b51 ELC2 CRC check, čištění 2024-02-07 13:36:25 +01:00
37d02abd3f oddělení, čištění, kontrola ELC1 2024-02-05 15:04:22 +01:00
5229f16c9d oddeleni a lazeni ELC1 2024-02-01 15:07:33 +01:00
c0b36e9068 Oddělení ELC1 generatoru a readeru 2024-01-31 14:19:23 +01:00
a7fc519138 oddělení generatoru od readeru 2024-01-29 14:50:12 +01:00
36a799057c upravy 2024-01-24 08:25:44 +01:00
f260e92596 upravy čištění 2023-12-18 08:01:34 +01:00
3954e0f6a5 upravy 2023-12-11 08:00:24 +01:00
892ae13bf2 čištění a další upravy 2023-12-08 10:30:44 +01:00
f92b2c708f ELC 2 2023-12-07 14:51:36 +01:00
31c23daf5e string clean 2023-08-30 15:37:57 +02:00
051a13e697 clean and hub 2023-08-30 09:15:13 +02:00
15de81ddf2 code cleaning 2023-08-29 15:15:06 +02:00
865493c984 vymazání odřádkování 2023-08-28 09:38:26 +02:00
ed2cf088a6 uprava souboru 2023-08-28 08:01:54 +02:00
eaf88b506a implementace pugi xml 2023-08-25 14:14:45 +02:00
b2260178f6 generování s cestou 2023-08-18 12:21:27 +02:00
139 changed files with 19269 additions and 2240 deletions

21
.vscode/c_cpp_properties.json vendored Normal file
View File

@@ -0,0 +1,21 @@
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.22000.0",
"compilerPath": "g++.exe",
// "cStandard": "c99",
"cppStandard": "c++20", //ex=c++20
"intelliSenseMode": "gcc-x86"
}
],
"version": 4
}

21
.vscode/settings.json vendored
View File

@@ -65,7 +65,26 @@
"bitset": "cpp",
"codecvt": "cpp",
"xtree": "cpp",
"map": "cpp"
"map": "cpp",
"csignal": "cpp",
"filesystem": "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",
"climits": "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 -std=c++11
# define library paths in addition to /usr/lib
# if I wanted to include libraries not in /usr/lib I'd specify
@@ -16,13 +16,13 @@ CXXFLAGS := -Wall -Wextra -g -lssl -lcrypto -w
LFLAGS =
# define output directory
OUTPUT := output
OUTPUT:= output
# define source directory
SRC := src
SRC := src src/common src/reader src/generator
# define include directory
INCLUDE := include
INCLUDE := include include/common include/reader include/generator
# define lib directory
LIB := lib

View File

@@ -2,11 +2,18 @@
Generování licence pro SD kartu
## version 1.1
- oprava #define direktiv pro celý kod (zapínání debugu, detailního výpisu a kompletního zakomentování kodu)
## version 1.0
- startovací publikační verze. Implementováno generování a čtení ELC1, ELC2 i ELC3
## Docker
/bin/bash
- docker-compose up, spustí kontejner
- otevření terminálu konterjneru, docker exec -it sd_gen-sd_gen-1 /bin/bash
- otevření terminálu kontejneru, docker exec -it sd_gen-sd_gen-1 /bin/bash
./generate.sh - vytvoření spustitelného souboru
./start.sh - spuštění spustistelného souboru
./generate.sh
./start.sh

View File

@@ -8,6 +8,18 @@ RUN chmod 755 /app/generate.sh
COPY ./start.sh /app/
RUN chmod 755 /app/start.sh
COPY ./startok.sh /app/
RUN chmod 755 /app/startok.sh
COPY ./startuid.sh /app/
RUN chmod 755 /app/startuid.sh
COPY ./lread.sh /app/
RUN chmod 755 /app/lread.sh
COPY ./lgen.sh /app/
RUN chmod 755 /app/lgen.sh
COPY ./Makefile /app/
ENTRYPOINT ["tail"]

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 -w -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

@@ -1,5 +1,2 @@
#!/bin/bash
rm src/CreateLicence.o
rm src/PlcLicence.o
rm src/utils.o
make

7
docker/lgen.sh Normal file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
chmod 777 output/generate
#./output/generate -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml
cd output
./generate -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml

7
docker/lread.sh Normal file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
chmod 777 output/read
#./output/read -cid=0353445355313647801b1a9f6600c747 -csd=0353445355313647801b1a9f6600c747 -outputType=file -configFileName=licData.xml
cd output
./read -cid=0353445355313647801b1a9f6600c747 -csd=0353445355313647801b1a9f6600c747 -outputType=file -configFileName=licData.xml

View File

@@ -1,7 +1,7 @@
#!/bin/bash
chmod 777 output/licenceGenerator
#./output/licenceGenerator -cid=9f544930303030300000000b47015423 -csd=400e00325b5900003a0d7f800a40008d -outputType=file -configFileName=licData.xml
#./output/licenceGenerator -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml
cd output
./licenceGenerator -cid=9f544930303030300000000b47015423 -csd=400e00325b5900003a0d7f800a40008d -outputType=file -configFileName=licData.xml
./licenceGenerator -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml

7
docker/startELC12.sh Normal file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
chmod 777 output/licenceGenerator
#./output/licenceGenerator -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml
cd output
./licenceGenerator -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml

7
docker/startok.sh Normal file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
chmod 777 output/licenceGeneratorok
#./output/licenceGeneratorok -cid=9f5449534443495461457815de0164a9 -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml -licenceFileName=ezlic_eovosv0_vaxvcpalxjx.lic -licenceVersion=1 -licenceType=EOV_OSV
cd output
./licenceGeneratorok -cid=9f5449534443495461457815de0164a9 -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml -licenceFileName=ezlic_eovosv0_vaxvcpalxjx.lic -licenceVersion=1 -licenceType=EOV_OSV

7
docker/startuid.sh Normal file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
chmod 777 output/licenceGenerator
#./output/licenceGenerator -uid=a3395d1b898b4fdbbd563f9c75b3e885 -outputType=file -configFileName=licData.xml
cd output
./licenceGenerator -uid=a3395d1b898b4fdbbd563f9c75b3e885 -outputType=file -configFileName=licData.xml

BIN
ezlic_drt0_jjacdgpdxpb.lic Normal file

Binary file not shown.

81
include/common/SDCard.h Normal file
View File

@@ -0,0 +1,81 @@
#ifndef SDCARD_H_
#define SDCARD_H_
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#define CID_LENGTH 32
#define CSD_LENGTH 32
using namespace std;
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;
const BYTE cnibblescount = 32;
const string cidFilePath = "";
struct SDCardInfo
{
uint32_t cardSize{};
uint32_t serialNumber{};
string date = "";
string oemID = "";
string name = "";
bool isLoaded = false;
};
class SDCard
{
struct SDCardData
{
uint8_t isCorrectLoad = 0; // SD karta je korektne nactena //bool vs byte ?
uint8_t CID_nibble[32] = {0}; // surova data CID ze souboru
uint8_t CID[16] = {0}; // prekodovane CID informace
uint8_t 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);
uint8_t productRevision_hw = 0;
uint8_t productRevision_sw = 0;
float productRevision = 0; // revize produktu 1B [bcd sh] -> Byte 7, bity 0-3 = revize HW, bity 4-7 = revize SW
uint32_t serialNumber = 0; // seriove cislo karty 4B -> Byte 3-6
uint16_t manufacturerDate_year = 0;
uint8_t manufacturerDate_month = 0;
string date = "";
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
uint8_t CRCOK = 0; // CRC 1B -> Byte 0, bity 1-7, bit 0 je vzdy = 1
uint8_t CSD_nibble[32] = {}; //: ARRAY [0..31] OF BYTE; // surova data CSD ze souboru
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();
bool getCIDFromFile();
bool getCSDFromFile();
public:
SDCardData cardData;
bool isLoaded = false;
char cid[32] = {};
char csd[32] = {};
string filePath = "";
string cidString = ""; // pro předání pro starý generátor
string csdString = ""; // pro předání pro starý generátor
SDCard();
SDCard(string cid, string csd);
SDCard(const string filesPath);
};
#endif
#endif

View File

@@ -0,0 +1,7 @@
#ifndef LICCONNECTOR_H_INCLUDED
#define LICCONNECTOR_H_INCLUDED
#include "lic_config.h"
//#include "../../_src/_main/Ez_automaincfg.h"
#endif // LICCONNECTOR_H_INCLUDED

View File

@@ -0,0 +1,7 @@
#ifndef LIC_CONFIG_H_INCLUDED
#define LIC_CONFIG_H_INCLUDED
//#define EZ_LIC_DEBUG //zapíná debug pro windows. Pro produkci je potřeba nechat zakomentované
//#define EZ_LIC_DEBUG_SHOW_DETAILS //zapíná detailní výpis při čtení licene. Pro produkci je potřeba nechat zakomentované
#endif

View File

@@ -0,0 +1,241 @@
#ifndef LICENCE_COMMON_H_
#define LICENCE_COMMON_H_
#include "licConnector.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#define CRC = 1
//---------------- společná hlavička pro všechny licence ----------------
#include <cstring>
#include <string>
#include <unordered_map>
#include <map>
#include <stdint.h>
using namespace std;
#define XML_VERSION 1
#define SOFTWARE_VERSION 1
#define SUCCES 0
#define CRYPT_INIT_VECTOR_SIZE 16
#define CRYPT_INIT_KEY_SIZE 32
const int cidSize = 32;
const int csdSize = 32;
const int generatorVersion = 1;
typedef uint8_t BYTE;
typedef uint16_t WORD;
typedef uint32_t DWORD;
typedef uint32_t DATE;
enum class GeneralError
{
GeneralError = 1,
FileOpenError = 2,
FileReadError = 3,
FileWriteError = 4,
ELCNotImplemented = 5,
LicenceTypeNotImplemented = 6,
CompatibilityTypeNotImplemented = 7,
ELCMismatch = 8,
CRCMismatch = 9,
EncryptError = 10,
DecryptError = 11,
ParamMissing = 12,
IvanlidParam = 13,
SDCardReadError = 50,
LicenceReadError = 51,
LicenceSizeMismatch = 52,
LicenceSizeCardMismatch = 53,
LicenceMismatch = 54,
LicenceCRCMismatch = 54,
UIDReadError = 55,
ItemsCountMismatch = 61
};
enum class ELCType
{
ELC1 = 1, // starý původní licenční soubor zalozený na CID a CSD
ELC2 = 2, // modifikovaný starý licenční soubor umoznující modifikace (šifrování, název) dle parametrů
ELC3 = 3 // budoucí softwarový licenční soubor, který není zalozený na existenci CID a CSD, ale na unikátním ID instalace linuxu
};
enum class ELCSubType
{
DEFAULT = 1
}; // subtype = dataVersion
enum class LicenceType
{
EOS_EOV,
DDTS,
DRT
}; //
enum class HeaderType
{
DEFAULT = 0
}; ////subtype = version
enum class EncryptionType
{
CID_AES256 = 10,
FIX_AES256 = 20
};
enum class BinaryType
{
FILE = 1,
BASE64 = 2
};
enum class PlcType
{
WAGO = 1,
TECO = 2
};
enum class FileNameGenerationType
{
DEFAULT = 1
};
struct CryptInitVector{ int vec[CRYPT_INIT_VECTOR_SIZE]; };
struct CryptAesKey { int key[CRYPT_INIT_KEY_SIZE]; };
// indexy musí být velká písmena ze základní ASCI tabulky
struct Mapping
{
unordered_map<string, LicenceType> licMapTypes = {{"EOV_OSV", LicenceType::EOS_EOV}, {"DDTS", LicenceType::DDTS}, {"DRT", LicenceType::DRT}};
unordered_map<string, EncryptionType> licMapEncryption = {{"CID_AES256", EncryptionType::CID_AES256}, {"FIX_AES256", EncryptionType::FIX_AES256}};
unordered_map<string, PlcType> licMapPlcType = {{"WAGO", PlcType::WAGO}, {"TECO", PlcType::TECO}};
};
struct ErrorMessage
{
int code = 0;
string message = "";
};
struct LicenceIdentification
{
ELCType licElcType = ELCType::ELC2; // hlavní typ licenčního souboru
LicenceType licLicenceType;
string licTypeName = "";
PlcType licPlcType;
uint8_t licenceVersion = 1; // verze licence, určuje kodování, pojmenování souborů
uint8_t licenceIndex = 0; // index licenčního souboru v případě, ze jich je víc
uint8_t revision;
uint8_t licCompatibility = 0; // identikator hlavního ELC. 0 = nedefinová a vrací se defaultní k danému ELC
uint16_t licItemsCount = 0;
string cid_cds_path = "";
string licenceFilePath = "";
};
/// @brief obecná struktura pro reader
struct LicenceInfoGeneral
{
map<DWORD, DWORD> licences = {};
};
/// @brief obecná struktura polozky licence, defaultní kompatibilita
struct LicenceItem
{
DWORD protocolId{};
DWORD dataPointsCount{};
};
/* struktury pro ELC 1 */
// defaultní struktura pro ELC 1
struct LicenceELC1Info
{
bool isValid{false};
};
// struktura ELC1, kompatibilita 1
struct LicenceELC1Info_1
{
unordered_map<int, int> licences = {};
};
// defaultni struktura polozky licence ELC 1
struct LicenceELC1Item
{
int protocolId = -1;
int dataPointsCount = 0;
};
/* struktury pro ELC 2 */
// defaultní struktura pro ELC 2
struct LicenceELC2Info
{
map<DWORD, DWORD> licences = {};
};
/* struktury pro ELC 3 */
// defaultní struktura pro ELC 3
struct LicenceELC3Info
{
map<DWORD, DWORD> licences = {};
};
// struct LicenceELC2Info_1
// {
// map<int, int> licences = {};
// };
// defaultni struktura polozky ELC 2
struct LicenceELC2Item
{
DWORD protocolId{};
DWORD dataPointsCount{};
};
// struktura polozky ELC 2 pro další kompatibility
struct LicenceELC2Item_1
{
DWORD protocolId{};
DWORD dataPointsCount{};
};
// defaultni struktura polozky ELC 3
struct LicenceELC3Item
{
DWORD protocolId{};
DWORD dataPointsCount{};
};
// struktura polozky ELC 3 pro další kompatibility,
struct LicenceELC3Item_1
{
DWORD protocolId{};
DWORD dataPointsCount{};
};
class LicenceException : public std::exception
{
public:
LicenceException(int errorCode, const std::string &errorMessage)
: errorCode_(errorCode), errorMessage_(errorMessage) {}
const char *what() const noexcept override
{
return errorMessage_.c_str();
}
int getErrorCode() const
{
return errorCode_;
}
const std::string &getErrorMessage() const
{
return errorMessage_;
}
private:
int errorCode_;
std::string errorMessage_;
};
#endif
#endif

View File

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

View File

@@ -0,0 +1,88 @@
#ifndef PLC_LICENCE2_COMMON_H
#define PLC_LICENCE2_COMMON_H
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include <vector>
#include "licenceCommon.h"
#include "SDCard.h"
/// @brief společná třída pro pro reader i generator licence typu ELC2
class LicenceELC2
{
public:
LicenceELC2();
LicenceELC2(LicenceIdentification &licIdentification);
~LicenceELC2();
string cid_cdsPath = "";
string licenceFilePath = "";
string licFileName = "";
Mapping mapping;
ErrorMessage errorMessage;
struct LicenceId
{
char licIdent[5] = {'E', 'L', 'C', '0', '_'};
};
// struct __attribute__((__packed__)) LicencePublicHeader
struct LicenceIdentDataHeader
{
BYTE licenceType{}; // EOSEOV, DRT ...
BYTE licenceTypeVersion = 1; // verze licence, urcuje nuance sifrování a pojmenování souborů
BYTE licenceIndex{}; // puvodní post fix, identifikátor pro více licencí
BYTE compatibilityVersion = 1; // udava verzi komplet PrivateContent
BYTE licItemCount{}; // počet protokolů v linenci
WORD publicHeaderLength{}; // délka veřejné hlavičy
WORD cardSize{}; // velikost SD karty
DWORD serialNumber = {}; // seriove cislo karty
};
struct licDataItem
{
DWORD protoId{}; // id protokolu pro ktery je licence
DWORD licCount{}; // pocet datovych bodu licence
};
struct PublicHeader
{
string version = "";
string projectDescription = "";
string date = "";
string licenceType = "";
};
struct PrivateContent // privátní šifrovaná část
{
LicenceIdentDataHeader licenceIdentHeader{};
vector<licDataItem> dataItems{};
WORD crc{};
};
struct LicenceBody
{
LicenceId licId{};
LicenceIdentDataHeader licenceIdentHeader{};
string publicHeader = ""; // JSON
PrivateContent privateContent{};
};
SDCard sdCard{};
protected:
vector<unsigned char> cryptPrivateContent(const std::vector<unsigned char> &content);
vector<unsigned char> decryptPrivateContent(const std::vector<unsigned char> &content);
void initVector(BYTE *iVector, BYTE *key);
string getLicenceName();
LicenceBody licBody{};
LicenceIdentification lIdentification{};
private:
};
#endif
#endif

View File

@@ -0,0 +1,90 @@
#ifndef PLC_LICENCE3_COMMON_H
#define PLC_LICENCE3_COMMON_H
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#define UID_LENGTH 32
#include <vector>
#include "licenceCommon.h"
/// @brief společná třída pro pro reader i generator licence typu ELC2
class LicenceELC3
{
public:
LicenceELC3();
LicenceELC3(LicenceIdentification &licIdentification);
~LicenceELC3();
string licenceFilePath = "";
string licFileName = "";
string uid = "";
BYTE uidb[UID_LENGTH] = {};
string uid_path = ""; ///etc/machine-id
Mapping mapping;
ErrorMessage errorMessage;
struct LicenceId
{
char licIdent[5] = {'E', 'L', 'C', '0', '_'};
};
// struct __attribute__((__packed__)) LicencePublicHeader
struct LicenceIdentDataHeader
{
BYTE licenceType{}; // EOSEOV, DRT ...
BYTE licenceTypeVersion = 1; // verze licence, urcuje nuance sifrování a pojmenování souborů
BYTE licenceIndex{}; // puvodní post fix, identifikátor pro více licencí
BYTE compatibilityVersion = 1; // udava verzi komplet PrivateContent
BYTE licItemCount{}; // počet protokolů v linenci
WORD publicHeaderLength{}; // délka veřejné hlavičy
// WORD cardSize{}; // velikost SD karty
// DWORD serialNumber = {}; // seriove cislo karty
};
struct licDataItem
{
DWORD protoId{}; // id protokolu pro ktery je licence
DWORD licCount{}; // pocet datovych bodu licence
};
struct PublicHeader
{
string version = "";
string projectDescription = "";
string date = "";
string licenceType = "";
};
struct PrivateContent // privátní šifrovaná část
{
LicenceIdentDataHeader licenceIdentHeader{};
vector<licDataItem> dataItems{};
WORD crc{};
};
struct LicenceBody
{
LicenceId licId{};
LicenceIdentDataHeader licenceIdentHeader{};
string publicHeader = ""; // JSON
PrivateContent privateContent{};
};
protected:
vector<unsigned char> cryptPrivateContent(const std::vector<unsigned char> &content);
vector<unsigned char> decryptPrivateContent(const std::vector<unsigned char> &content);
void initVector(BYTE *iVector, BYTE *key);
string getLicenceName();
LicenceBody licBody{};
LicenceIdentification lIdentification{};
private:
};
#endif
#endif

75
include/common/utils.h Normal file
View File

@@ -0,0 +1,75 @@
#ifndef UTILS_H_
#define UTILS_H_
#include "licConnector.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
#include <chrono>
#include <libgen.h>
#include <unistd.h>
typedef uint8_t BYTE;
typedef uint16_t WORD;
typedef uint32_t DWORD;
typedef uint32_t DATE;
using namespace std;
struct DateAndTime {
uint16_t date; // DATE data type in CODESYS
uint16_t time; // TIME data type in CODESYS
};
void generatePause();
std::string right(const std::string& sourceString, size_t numChars);
void getCharsFromString(const string source, char *charArray);
uint16_t calculateCRC16(const uint8_t* data, size_t length);
WORD getCurrentDateAsCODESYSDate();
DWORD getCurrentDateAsCODESYSDateDword();
DateAndTime getCurrentDateTimeAsCODESYSDateTime();
DATE getLicDate();
string getDate();
int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext);
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);
string base64_encode_ai(const std::string &input);
unordered_map<string, string> getArguments(int argc, char *argv[]);
void getCharsFromString(string& source, char *charArray, size_t length);
string getCompletePath(string fileName);
void appendStringToVector(const std::string& str, std::vector<unsigned char>& charVector);
uint16_t calculateCRC16(std::vector<unsigned char>& charVector);
uint16_t calculateCRC16(std::vector<char> &charVector);
uint16_t calculateCRC16(std::vector<unsigned char> &charVector, int removeCount);
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);
bool readFile(string fileName, vector<char> &output);
#endif
#endif

View File

@@ -0,0 +1,38 @@
#ifndef ELC1_GENERATOR__H
#define ELC1_GENERATOR__H
#include "utils.h"
#include "licenceCommon.h"
#include "licenceELC1.h"
#include "SDCard.h"
#include "pugixml.hpp"
namespace Generator
{
class Licence1 : public LicenceELC1
{
public:
Licence1();
Licence1(string cid, string csd, string dataFileName);
~Licence1();
pugi::xml_document *xmlDoc;
string projectDescription = "";
string stationName; // name of station
string distributor;
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
void processConfigFile(string &dataFileName); // process data from config file
bool createLicence(); // create licence for EOV_OSV
LicenceIdentification lIdentification;
};
}
#endif

View File

@@ -0,0 +1,40 @@
#ifndef ELC2_GENERATOR_H
#define ELC2_GENERATOR_H
#include "utils.h"
#include "licenceCommon.h"
#include "licenceELC2.h"
#include "SDCard.h"
#include "pugixml.hpp"
using namespace std;
namespace Generator
{
class Licence2 : public LicenceELC2
{
public:
Licence2();
Licence2(string cid, string csd, pugi::xml_document * xmlDoc);
~Licence2();
string cid = "";
string csd = "";
pugi::xml_document *xmlDoc;
string projectDescription = "";
bool createLicence();
private:
void getHeader();
string getVersion(int middleVersion);
bool processInputConfiguration();
void getLicenceItems();
};
}
#endif

View File

@@ -0,0 +1,38 @@
#ifndef ELC3_GENERATOR_H
#define ELC3_GENERATOR_H
#include "utils.h"
#include "licenceCommon.h"
#include "licenceELC3.h"
#include "pugixml.hpp"
using namespace std;
namespace Generator
{
class Licence3 : public LicenceELC3
{
public:
Licence3();
Licence3(string uuid, pugi::xml_document * xmlDoc);
~Licence3();
string cid = "";
string csd = "";
pugi::xml_document *xmlDoc;
string projectDescription = "";
bool createLicence();
private:
void getHeader();
string getVersion(int middleVersion);
bool processInputConfiguration();
void getLicenceItems();
};
}
#endif

View File

@@ -0,0 +1,69 @@
#include "licenceCommon.h"
#ifndef LICENCE_GENERATOR_H_
#define LICENCE_GENERATOR_H_
#define DEFAULT_LICENCE_POINTS_COUNT = 4294967295 //počet licenčních bodů pro některé protokoly např: pt_Ez_buffer a pt_Ez_webs
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdint.h>
#include "pugixml.hpp"
#include "licGenELC1.h"
#include "licGenELC2.h"
#include "licGenELC3.h"
using namespace std;
class LicenceGenerator
{
public:
struct LicData
{
string station = "";
string distributor = "";
string licenceName = "";
string projectDescription = "";
string cid = ""; // CID z SD karty
string csd = ""; // CSD z SD karty
string uid = ""; // jedinečný identifikátor z jiného systému
pugi::xml_document *doc;
};
LicData licData {};
int elcSwitchType {};
string operationErrors = "";
pugi::xml_document doc {} ;
bool argumentsCorrect = false;
ErrorMessage error {};
// LicenceELC11 *licence11;
// LicenceELC21 *licence21;
// LicenceELC31 *licence31;
Mapping mapping {};
SDCard sdCard {};
LicenceGenerator();
~LicenceGenerator();
LicenceGenerator(string uid, string cid, string csd, string dataFileName);
void createLicenceFile();
LicenceInfoGeneral licenceInfoGeneral {};
private:
LicenceIdentification licIdentification;
string configFileName = "";
void *licence = nullptr;
bool processInputConfiguration();
void createLicenceELC1();
void createLicenceELC2();
void createLicenceELC3();
};
#endif

View File

@@ -0,0 +1,74 @@
/**
* pugixml parser - version 1.7
* --------------------------------------------------------
* Copyright (C) 2006-2015, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
* Report bugs and download new versions at http://pugixml.org/
*
* This library is distributed under the MIT License. See notice at the end
* of this file.
*
* This work is based on the pugxml parser, which is:
* Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
*/
#ifndef HEADER_PUGICONFIG_HPP
#define HEADER_PUGICONFIG_HPP
// Uncomment this to enable wchar_t mode
// #define PUGIXML_WCHAR_MODE
// Uncomment this to enable compact mode
// #define PUGIXML_COMPACT
// Uncomment this to disable XPath
// #define PUGIXML_NO_XPATH
// Uncomment this to disable STL
// #define PUGIXML_NO_STL
// Uncomment this to disable exceptions
// #define PUGIXML_NO_EXCEPTIONS
// Set this to control attributes for public classes/functions, i.e.:
// #define PUGIXML_API __declspec(dllexport) // to export all public symbols from DLL
// #define PUGIXML_CLASS __declspec(dllimport) // to import all classes from DLL
// #define PUGIXML_FUNCTION __fastcall // to set calling conventions to all public functions to fastcall
// In absence of PUGIXML_CLASS/PUGIXML_FUNCTION definitions PUGIXML_API is used instead
// Tune these constants to adjust memory-related behavior
// #define PUGIXML_MEMORY_PAGE_SIZE 32768
// #define PUGIXML_MEMORY_OUTPUT_STACK 10240
// #define PUGIXML_MEMORY_XPATH_PAGE_SIZE 4096
// Uncomment this to switch to header-only version
// #define PUGIXML_HEADER_ONLY
// Uncomment this to enable long long support
// #define PUGIXML_HAS_LONG_LONG
#endif
/**
* Copyright (c) 2006-2015 Arseny Kapoulkine
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

File diff suppressed because it is too large Load Diff

View File

@@ -1,247 +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
};
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; // DWORD = unsigned 32 bit value
typedef uint16_t WORD; // WORD = unsigned 16 bit value
typedef uint8_t BYTE; // BYTE = unsigned 8 bit value
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; // CID
string csdString = "";
char *csd; // 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
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 licencname
void initCrypto(); // inits keys and vectors for encryptin
unsigned char *getLicenceContent(); // reads content of licence
public:
string operationErrors = "";
PlcLicence();
PlcLicence(char *cid, char *csd, char *stationName, char *switchName, char *licenceType, char *binaryType, const char *dataFileName);
PlcLicence(string cid, string csd, char *stationName, char *switchName, char *licenceType, char *binaryType, const char *dataFileName);
PlcLicence(map<string, string> & arguments);
PlcLicence(char *cid, char *csd, string binaryType, string dataFileName);
bool CreateLicence(); // creates licence
bool ReadLicence(const char *dataFileName, WORD licType, BYTE licPostfix, char *cid, char *csd); // reads licence file to readable structures
};
#endif

View File

@@ -0,0 +1,34 @@
#ifndef ELC1_READER__H
#define ELC1_READER__H
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include "licenceCommon.h"
#include "licenceELC1.h"
#include "SDCard.h"
using namespace std;
namespace Reader
{
class Licence1 : public LicenceELC1
{
public:
LicenceELC1Info licenceInfo;
Licence1();
~Licence1();
Licence1(LicenceIdentification &licIdentification);
bool readLicence(LicenceInfoGeneral *licences);
bool getLicenceInfo(void *ptr);
bool getLicenceItemInfo(int protocolId, void *returnItemStructure);
void getLicenceItems();
};
}
#endif
#endif

View File

@@ -0,0 +1,32 @@
#ifndef ELC2_READER_H
#define ELC2_READER_H
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include "licenceCommon.h"
#include "licenceELC2.h"
#include "SDCard.h"
using namespace std;
namespace Reader
{
class Licence2 : public LicenceELC2
{
public:
LicenceELC2Info licenceInfo;
Licence2();
~Licence2();
Licence2(LicenceIdentification &licIdentification);
bool readLicence(LicenceInfoGeneral *licences);
bool getLicenceInfo(void *ptr);
void getLicenceItems();
};
}
#endif
#endif

View File

@@ -0,0 +1,32 @@
#ifndef ELC3_READER__H
#define ELC3_READER__H
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include "licenceCommon.h"
#include "licenceELC3.h"
namespace Reader
{
class Licence3 : public LicenceELC3
{
public:
LicenceELC3Info licenceInfo;
Licence3();
~Licence3();
Licence3(LicenceIdentification &licIdentification);
bool readLicence(LicenceInfoGeneral *licences);
bool getLicenceInfo(void *ptr);
void getLicenceItems();
private:
bool getUID();
};
}
#endif
#endif

View File

@@ -0,0 +1,63 @@
#ifndef LICENCE_READER_H_
#define LICENCE_READER_H_
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include "SDCard.h"
#include "licReaderELC1.h"
#include "licReaderELC2.h"
#include "licReaderELC3.h"
using namespace std;
using namespace Reader;
struct InitStructure
{
int licenceType = 0;
int licenceVersion = 0;
int licenceIndex = 0;
int compatibility = 0;
string licenceFilePath = "";
string cid_csd_filePath = "";
string uid_filePath = "";
};
/// @brief struktura pro informaci o licenci
struct LicenceInfo
{
string licenceFileName = ""; //samotný název licenčního souboru
string licenceFilePath = ""; //název licenčního souboru včetně cesty
};
class LicenceReader
{
public:
int elcSwitchType;
string operationErrors = "";
bool argumentsCorrect = false;
ErrorMessage error;
SDCardInfo sdCardInfo {};
LicenceInfo licInfo {};
LicenceReader();
~LicenceReader();
bool init(int elcType, InitStructure &initStructure);
bool initread(int elcType, InitStructure &initStructure);
bool getLicenceInfo(void *returnStructure); //vrací informace o všech licenčních bodech základě předané návratové struktury
bool getLicenceItemInfo(int protocolId, void *returnItemStructure); //vrací informace o licenčím bodu na základě id protocolu a předané návratové struktury
private:
Licence3 *licence3 {}; //interní struktura pro zpracování licence ELC2
Licence2 *licence2 {}; //interní struktura pro zpracování licence ELC2
Licence1 *licence1 {}; //interní struktura pro zpracování licence ELC1
LicenceIdentification licIdentification {};
string configFileName = "";
LicenceInfoGeneral licencesInfo {}; //pole licencí
};
#endif
#endif

View File

@@ -1,83 +0,0 @@
#include <iostream>
#include <stdlib.h>
#include <chrono>
#include <bitset>
#include <map>
#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
#ifndef BYTE
typedef uint8_t BYTE;
#endif
#ifndef WORD
typedef uint16_t WORD;
#endif
#ifndef DWORD
typedef uint32_t DWORD;
#endif
#ifndef DATE
typedef uint32_t DATE;
#endif
using namespace std;
struct DateAndTime {
uint16_t date; // DATE data type in CODESYS
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();
int encrypt(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(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);
map<string, string> getArguments(int argc, char *argv[]);
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);

8
licData.xml Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<licence elc="1" xmlVersion="1" revision="1" compatibility="1">
<licenceType licenceVersion="1" licenceIndex="0">EOV_OSV</licenceType>
<plcType>wago</plcType>
<licenceName>Licence pro EOV_OSV</licenceName>
<station>zst.ceskatrebova.ddts.cz</station>
<distributor>ROV21</distributor>
</licence>

5
output/cid Normal file
View File

@@ -0,0 +1,5 @@
9f54495344434954615ad803c50171bf
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 -uid=a3395d1b898b4fdbbd563f9c75b3e885.a433 -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml

1
output/createnewELC2.bat Normal file
View File

@@ -0,0 +1 @@
licenceGenerator.exe -cid=9f54495344434954615ad803c50171bf -csd=400e00325b5900003be77f800a400043 -outputType=file -configFileName=licData.xml

2
output/csd Normal file
View File

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

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
output/generate Normal file

Binary file not shown.

5
output/lcis/cid 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

5
output/lcis/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

2
output/lcis/csd Normal file
View File

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

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

37
output/lcis/licData.xml Normal file
View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8" ?>
<licence elc="2" xmlVersion="1" revision="1" compatibility="1">
<licenceType licenceVersion="1" licenceIndex="0">EOV_OSV</licenceType>
<plcType>WAGO</plcType>
<licenceName>Licence pro EOV_OSV</licenceName>
<station>eov.ceskatrebova.ddts.cz</station>
<distributor>eov2</distributor>
<project>Projekt XXX stanice YYY</project>
<items>
<item>
<name>Položka licence 1</name>
<protoId>111</protoId>
<dataPointsCount>100</dataPointsCount>
</item>
<item>
<name>Položka licence 2</name>
<protoId>222</protoId>
<dataPointsCount>200</dataPointsCount>
</item>
<item>
<name>Položka licence 3</name>
<protoId>333</protoId>
<dataPointsCount>300</dataPointsCount>
</item>
<item>
<name>Položka licence 4</name>
<protoId>555</protoId>
<dataPointsCount>666</dataPointsCount>
</item>
<item>
<name>Položka licence 5</name>
<protoId>666</protoId>
<dataPointsCount>9998</dataPointsCount>
</item>
</items>
</licence>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,8 +1,39 @@
<?xml version="1.0" encoding="UTF-8" ?>
<data version="1">
<plcType>WAGO</plcType>
<licenceType version="1">EOV_OSV</licenceType>
<licenceName>Licence pro EOV_OSV</licenceName>
<station>ceskatrebova</station>
<distributor>RO1</distributor>
</data>
<licence elc="3" xmlVersion="1" revision="1" compatibility="1">
<licenceType licenceVersion="1" licenceIndex="0">DRT</licenceType>
<plcType>wago</plcType>
<licenceName>Licence pro EOV_OSV</licenceName>
<project>Licence ELC3</project>
<items>
<item>
<name>pt_Ez_interHW</name>
<protoId>0</protoId>
<dataPointsCount>3</dataPointsCount>
</item>
<item>
<name>pt_Ez_buffer</name>
<protoId>1</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_webs</name>
<protoId>2</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104c</name>
<protoId>5</protoId>
<dataPointsCount>55</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104s</name>
<protoId>6</protoId>
<dataPointsCount>66</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec61850c</name>
<protoId>7</protoId>
<dataPointsCount>77</dataPointsCount>
</item>
</items>
</licence>

39
output/licDataActual3.xml Normal file
View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" ?>
<licence elc="3" xmlVersion="1" revision="1" compatibility="1">
<licenceType licenceVersion="1" licenceIndex="0">DRT</licenceType>
<plcType>wago</plcType>
<licenceName>Licence pro EOV_OSV</licenceName>
<project>Licence ELC3</project>
<items>
<item>
<name>pt_Ez_interHW</name>
<protoId>0</protoId>
<dataPointsCount>3</dataPointsCount>
</item>
<item>
<name>pt_Ez_buffer</name>
<protoId>1</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_webs</name>
<protoId>2</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104c</name>
<protoId>5</protoId>
<dataPointsCount>55</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104s</name>
<protoId>6</protoId>
<dataPointsCount>66</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec61850c</name>
<protoId>7</protoId>
<dataPointsCount>77</dataPointsCount>
</item>
</items>
</licence>

39
output/licDataELC1.xml Normal file
View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" ?>
<licence elc="1" xmlVersion="1" revision="1" compatibility="1">
<licenceType licenceVersion="1" licenceIndex="0">EOV_OSV</licenceType>
<plcType>wago</plcType>
<licenceName>Licence pro EOV_OSV</licenceName>
<project>Zdenda Test CRC4</project>
<items>
<item>
<name>pt_Ez_interHW</name>
<protoId>0</protoId>
<dataPointsCount>3</dataPointsCount>
</item>
<item>
<name>pt_Ez_buffer</name>
<protoId>1</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_webs</name>
<protoId>2</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104c</name>
<protoId>5</protoId>
<dataPointsCount>55</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104s</name>
<protoId>6</protoId>
<dataPointsCount>66</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec61850c</name>
<protoId>7</protoId>
<dataPointsCount>77</dataPointsCount>
</item>
</items>
</licence>

39
output/licDataRDT2.xml Normal file
View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8" ?>
<licence elc="2" xmlVersion="1" revision="1" compatibility="1">
<licenceType licenceVersion="1" licenceIndex="0">DRT</licenceType>
<plcType>wago</plcType>
<licenceName>Licence pro EOV_OSV</licenceName>
<project>Zdenda Test CRC4</project>
<items>
<item>
<name>pt_Ez_interHW</name>
<protoId>0</protoId>
<dataPointsCount>3</dataPointsCount>
</item>
<item>
<name>pt_Ez_buffer</name>
<protoId>1</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_webs</name>
<protoId>2</protoId>
<dataPointsCount>4294967295</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104c</name>
<protoId>5</protoId>
<dataPointsCount>55</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec104s</name>
<protoId>6</protoId>
<dataPointsCount>66</dataPointsCount>
</item>
<item>
<name>pt_Ez_iec61850c</name>
<protoId>7</protoId>
<dataPointsCount>77</dataPointsCount>
</item>
</items>
</licence>

BIN
output/licenceGenerator Normal file

Binary file not shown.

BIN
output/licenceGeneratorok Normal file

Binary file not shown.

1
output/machine-id Normal file
View File

@@ -0,0 +1 @@
a3395d1b898b4fdbbd563f9c75b3e885

BIN
output/read Normal file

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

@@ -1,123 +1,79 @@
#include "reader/licenceReader.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include <stdio.h>
#include <map>
#include <cstring>
#include "plcLicence.h"
#include "utils.h"
#include <csignal>
#define FILEBUFFER 300
#define TWO_HOURSE_SECONDS 7200
void signalHandler(int signum)
{
if (signum == SIGSEGV)
{
std::cerr << "Caught segmentation fault (SIGSEGV)" << std::endl;
// You can perform some recovery actions here if needed
}
}
#include "licenceGenerator.h"
/// @brief hlavní funkce
/// @param argc
/// @param argv parametry pro generování licence
/// 1-cid, 2-csd, 3-stanice 4-rozvadec 5-typ licence
/// @return
int main(int argc, char *argv[])
int main8(int argc, char *argv[])
{
std::signal(SIGSEGV, signalHandler);
// a segmentation fault
// int* ptr = nullptr;
//*ptr = 42; // This will trigger a segmentation fault
// map<string, const char *> arguments = mapArguments(argc, argv);
map<string, string> argumentsString = getArguments(argc, argv);
// std::cout << "Number of arguments: " << argc << std::endl;
// if (argc > 1)
// {
// for (int i = 1; i < argc; ++i)
// {
// arguments.insert(make_pair(to_string(i), argv[i]));
// }
// }
// else
// cerr << "Invalid arguments count";
// for (auto it = argumentsString.begin(); it != argumentsString.end(); ++it)
// {
// std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
// std::cout << it->second.length() << std::endl;
// }
// generatePause();
// return 1;
// for (int i = 0; i < argc; ++i)
// {
// std::cout << "Argument " << i << ": " << argv[i] << std::endl;
// cout << "size: " << strlen(argv[i]);
// }
// generatePause();
// return 1;
// if (argc >= 5)
// {
// cid = argv[1];
// csd = argv[2];
// stationName = argv[3];
// switchName = argv[4];
// licenceType = argv[5];
// }
// else
// {
// cout << "Par count error" << endl;
// }
// if (argc <= 1)
// {
// cid = "9f544930303030300000000b47015423";
// csd = "400e00325b5900003a0d7f800a40008d";
// stationName = "ceskatrebova";
// switchName = "RO1";
// licenceType = "2";
// binaryType = "2";
// }
// else
// {
// cid = argv[1];
// csd = argv[2];
// }
// cid = "9f544930303030300000000b47015423";
// csd = "400e00325b5900003a0d7f800a40008d";
// stationName = "ceskatrebova";
// switchName = "RO1";
// licenceType = "2";
// binaryType = "2";
// cout << "binaryType: " << binaryType;
// cout << "CID:" << argumentsString["-cid"];
// cout << "final-cids: " << argumentsString["-cid"].length() << endl;
// cout << "final-cds: " << argumentsString["-csd"].length() << endl;
// cout << "-----------------------------------\n";
const int csdLength = argumentsString["-csd"].length();
char csdArg[32] = {};
getCharsFromString(argumentsString["-csd"], csdArg, csdLength);
const int cidLength = argumentsString["-cid"].length();
char cidArg[32] = {};
getCharsFromString(argumentsString["-cid"], cidArg, cidLength);
PlcLicence plcWriteLicence = PlcLicence(cidArg, csdArg, argumentsString["-outputType"], argumentsString["-configFileName"]);
if (plcWriteLicence.CreateLicence() == false)
unordered_map<string, string> arguments = getArguments(argc, argv);
try
{
cerr << "Licence creation failed";
unordered_map<string, string> arguments = getArguments(argc, argv);
LicenceGenerator generatorOld = LicenceGenerator(arguments["-uid"], arguments["-cid"], arguments["-csd"], arguments["-configFileName"]);
generatorOld.createLicenceFile();
//system("pause");
#ifdef READ
InitStructure initStructure = {};
initStructure.licenceType = (int)LicenceType::DRT;
initStructure.licenceVersion = 1;
initStructure.licenceIndex = 0;
initStructure.licenceFilePath = ""; //c://_projects//sd_gen//output//"; // cesta k licenčnímu souboru
initStructure.compatibility = 1;
// initStructure.compatibility = 0; v případě kompatibility 0 či nezadané je výstup defaultní.
// pro ELC 1 LicenceELC1Info je to isValid, pro ELC 2 strukura { int protocolId = -1; int dataPointsCount = 0; }
initStructure.cid_csd_filePath = ""; // cesta k cidu/csd pro načtení a kontrolu licence
initStructure.uid_filePath = ""; // cesta k souboru machine-id. (/etc/machine-id), takze by mělo být /etc/. machine-id si doplním
//---------------------------------------- ELC3 ----------------------------------------------------------
// verze ELC 3 pro jeden protokol. Oproti ELC2 je potřeba přidat cestu k uid/machine-id v initStructure
LicenceReader licenceReaderELC3{};
if (licenceReaderELC3.initread(3, initStructure)) // iniciacni nacteni
{
LicenceELC3Item info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
// if ()
int protocolId = 7;
// ukazka dat SD karty
cout << "název licenčního souboru: " << licenceReaderELC3.licInfo.licenceFileName << "\n";
cout << "cesta k licenčnímu souboru: " << licenceReaderELC3.licInfo.licenceFilePath << "\n";
if (licenceReaderELC3.getLicenceItemInfo(protocolId, &info))
{
cout << "Pocet licencních bodu pro " << info.protocolId << ": " << info.dataPointsCount << std::endl;
}
else
cout << "Tento protokol nemá body";
}
else
{
cout << "CHYBA: " << licenceReaderELC3.error.message;
}
//---------------------------------------- ELC3 ----------------------------------------------------------
system("pause");
return SUCCES;
#endif
return SUCCES;
}
catch (const LicenceException &ex)
{
cout << "error: " << ex.getErrorMessage();
system("pause");
}
catch (...)
{
cerr << "Obecná chyba\n";
system("pause");
}
return EXIT_SUCCESS;
system("pause");
return SUCCES;
}
#endif

View File

@@ -1,957 +0,0 @@
#include <cstring>
#include <fstream>
#include "plcLicence.h"
#include "utils.h"
#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 cEzLic_p78ou3_maxDataToFile = 10000; // velikost datoveho bufferu pro ulozeni dat licence
const BYTE cEzLic_p78ou3_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
PlcLicence::PlcLicence()
{
}
/// @brief process config file
/// @param dataFileName
void PlcLicence::processConfigFile(string &dataFileName)
{
std::string content;
std::ifstream inputFile(dataFileName);
if (inputFile.is_open())
{
content.assign((std::istreambuf_iterator<char>(inputFile)), (std::istreambuf_iterator<char>()));
inputFile.close();
//std::cout << "File content:\n" << content << std::endl;
}
else
{
std::cerr << "Unable to open the file." << std::endl;
}
string station = getXmlContentFromString(content, "station");
string distributor = getXmlContentFromString(content, "distributor");
// cout << station;
// cout << distributor;
this->stationName = station;
this->distributor = distributor;
// char stationCh[station.length()] = {};
// getCharsFromString(station, stationCh);
// char distributorCh[distributor.length()] = {};
// getCharsFromString(distributor, distributorCh);
// this->stationName = stationCh;
// this->distributor = distributorCh;
// cout << this->stationName << "\n";
// cout << this->distributor << "\n";
// this->stationName = "ceskatrebova";
// this->distributor = "RO1";
// cout << this->stationName << "\n";
// cout << this->distributor << "\n";
}
PlcLicence::PlcLicence(map<string, string> &arguments)
{
if (arguments.count("-cid") > 0)
{
const int cidLength = arguments["-cid"].length();
cout << "\n";
cout << "argument: " << arguments["-cid"] << endl;
cout << "argument delka: " << arguments["-cid"].length() << endl;
char cidArg[cidLength] = {};
getCharsFromString1(arguments["-cid"], cidArg);
this->cid = cidArg;
cout << "\n"
<< "CID 1:" << cid << " delka: " << strlen(cid) << "\n";
}
// this->cid = "9f544930303030300000000b47015423";
// this->csd = "400e00325b5900003a0d7f800a40008d";
cout << "\n"
<< "CID 2:"
<< " delka: " << strlen(cid) << "\n";
// if (arguments.count("-csd") > 0)
// {
// const int csdLength = arguments["-csd"].length();
// char csdArg[csdLength] = {};
// getCharsFromString(arguments["-csd"], csdArg);
// this->csd = csdArg;
// }
this->licType = 2;
if (arguments.count("-outputType") > 0)
{
if (arguments["-outputType"] == "base64")
this->binaryGeneration = BinaryGenerationType::Base64Cout;
else
this->binaryGeneration = BinaryGenerationType::File;
}
else
this->binaryGeneration = BinaryGenerationType::Base64Cout;
}
PlcLicence::PlcLicence(string cid, string csd, char *stationName, char *switchName, char *licenceType, char *binaryType, const char *dataFileName)
{
this->cidString = cid;
this->csdString = csd;
this->stationName = stationName;
this->distributor = switchName;
this->dataFileName = dataFileName;
this->licType = 2;
if (binaryType != nullptr)
{
if (binaryType[0] == '1')
this->binaryGeneration = BinaryGenerationType::Base64Cout;
else
this->binaryGeneration = BinaryGenerationType::File;
}
else
this->binaryGeneration = BinaryGenerationType::Base64Cout;
}
void PlcLicence::getSDData()
{
//int length = strlen(cid); // Get the length of the char array
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];
}
PlcLicence::PlcLicence(char *cid, char *csd, string binaryType, string dataFileName)
{
this->cid = cid;
this->csd = csd;
this->stationName = "";
this->distributor = "";
this->licType = 2;
processConfigFile(dataFileName);
if (binaryType == "base64")
this->binaryGeneration = BinaryGenerationType::Base64Cout;
else
this->binaryGeneration = BinaryGenerationType::File;
}
PlcLicence::PlcLicence(char *cid, char *csd, char *stationName, char *switchName, char *licenceType, char *binaryType, const char *dataFileName)
{
this->cid = cid;
this->csd = csd;
this->stationName = stationName;
this->distributor = switchName;
this->dataFileName = dataFileName;
this->licType = 2;
if (binaryType != nullptr)
{
if (binaryType[0] == '1')
this->binaryGeneration = BinaryGenerationType::Base64Cout;
else
this->binaryGeneration = BinaryGenerationType::File;
}
else
this->binaryGeneration = BinaryGenerationType::Base64Cout;
}
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);
}
}
unsigned char *PlcLicence::getLicenceContent()
{
getSDData();
initCrypto();
// promenne pro praci se soubory a adresari
DWORD sdFileHandle;
DWORD sdDirHandle;
string dirFileName;
string dirFilePath; //: STRING;
string dirInfo; //: DIRECTORY_INFO; - NAJIT
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[cEzLic_p78ou3_maxDataToFile]; // OF BYTE; data zapisovana do souboru
DWORD retDataCount; //: DWORD; // pocty zapisovanych a ctenych dat - navratova hodnota jednotlivych funkci
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; // = GetPlcData(dataFileName);// "licData.xml");
plcData.licenceName = "Licence";
plcData.licenceType = "1";
plcData.station = stationName; // "Test";
plcData.distributor = distributor; //"RO1";
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;
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();
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));
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];
return totalEncryptedArray;
}
}
return nullptr;
}
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); // 14 OK "v"
result += prefixChar + (this->sdData.CID[10] % 25); // 15 OK "a"
result += prefixChar + (this->sdData.CID_nibble[22] % 25); // 16 OK "x"
result += prefixChar + ((this->sdData.CID_nibble[23] * 2) % 25); // 17 OK "v"
result += prefixChar + (this->sdData.CID_nibble[24] % 25); // 18 not ok ... má být c = 99
result += prefixChar + ((this->sdData.CID_nibble[25] * 3) % 25); // 19 not ok a 112
result += prefixChar + (this->sdData.CID[9] % 25); // 20 OK
result += prefixChar + (this->sdData.CID[11] % 25); // 21 OK
result += prefixChar + (this->sdData.CID[2] % 25); // 22 OK
result += prefixChar + (this->sdData.CID[1] % 25); // 23 OK
result += prefixChar + (this->sdData.CID[3] % 25); // 24 OK
result += ".lic";
}
else
{
result = "ezlic_eovosv" + to_string(licPostfix) + "_";
result += prefixChar + (this->sdData.CID[12] % 25); // 14 OK "v"
result += prefixChar + (this->sdData.CID[10] % 25); // 15 OK "a"
result += prefixChar + (this->sdData.CID_nibble[22] % 25); // 16 OK "x"
result += prefixChar + ((this->sdData.CID_nibble[23] * 2) % 25); // 17 OK "v"
result += prefixChar + (this->sdData.CID_nibble[24] % 25); // 18 not ok ... má být c = 99
result += prefixChar + ((this->sdData.CID_nibble[25] * 3) % 25); // 19 not ok a 112
result += prefixChar + (this->sdData.CID[9] % 25); // 20 OK
result += prefixChar + (this->sdData.CID[11] % 25); // 21 OK
result += prefixChar + (this->sdData.CID[2] % 25); // 22 OK
result += prefixChar + (this->sdData.CID[1] % 25); // 23 OK
result += prefixChar + (this->sdData.CID[3] % 25); // 24 OK
result += ".lic";
}
return result;
}
struct PlcData GetPlcData(const char *dataFileName)
{
PlcData result;
result.plcType = "WAGO";
result.licenceName = "Licence 1";
result.licenceType = "";
result.licenceVersion = "1";
result.station = "";
result.distributor = "";
FILE *fp;
fp = fopen("licData.xml", "r"); // read mode
fseek(fp, 0, SEEK_END); // seek to end of file
int fileSize = ftell(fp); // get current file pointer
fseek(fp, 0, SEEK_SET);
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
int count = 0;
cout << "fileSize:" << fileSize << "\n";
char fileContent[3000];
for (int i = 0; i < fileSize; i++)
{
char c = fgetc(fp);
fileContent[i] = c;
cout << c;
// printf("%c", c);;
count++;
}
fclose(fp);
std::string fileContentStr(fileContent, sizeof(fileContent));
string typeContentString = getXmlContentFromString(fileContentStr, "type");
string nameContentString = getXmlContentFromString(fileContentStr, "name");
string stationContentString = getXmlContentFromString(fileContentStr, "station");
string switchContentString = getXmlContentFromString(fileContentStr, "switchboard");
cout << typeContentString << "\n";
cout << nameContentString << "\n";
cout << stationContentString << "\n";
cout << switchContentString << "\n";
if (typeContentString != "")
result.licenceType = typeContentString;
if (nameContentString != "")
result.licenceName = nameContentString;
if (stationContentString != "")
result.station = stationContentString;
if (switchContentString != "")
result.distributor = switchContentString;
return result;
}
bool PlcLicence::CreateLicence()
{
getSDData();
initCrypto();
// promenne pro praci se soubory a adresari
DWORD sdFileHandle;
DWORD sdDirHandle;
string dirFileName;
string dirFilePath;
string dirInfo;
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[cEzLic_p78ou3_maxDataToFile]; // OF BYTE; data zapisovana do souboru
DWORD retDataCount; //: DWORD; pocty zapisovanych a ctenych dat - navratova hodnota jednotlivych funkci
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;
; // = GetPlcData(dataFileName);// "licData.xml");
plcData.licenceName = "Licence";
plcData.licenceType = "1";
plcData.station = stationName; // "Test";
plcData.distributor = distributor; //"RO1";
LicenceSourceData licSourceData;
// cout << "size of WORD:" << sizeof(WORD) << endl;
// cout << "size of DWORD:" << sizeof(DWORD) << endl;
// cout << "size of DATE:" << sizeof(DATE) << endl;
// cout << "size of BYTE:" << sizeof(BYTE) << endl;
// cout << "size of int:" << sizeof(int) << endl;
// cout << "size of char:" << sizeof(char) << endl;
// cout << "size of float:" << sizeof(float) << endl;
// cout << "Size of dataToFile: " << sizeof(dataToFile) << endl;
// return true;
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;
switch (licIdent.licIDType)
{
case cEzLic_p78ou3_IDType_DDTS:
mainLicDescription = "ddts ";
break;
case cEzLic_p78ou3_IDType_EOVOSV:
mainLicDescription = "eov, osv ";
break;
default:
mainLicDescription = "neznama app ";
}
mainLicDescription += licSourceData.licPostfixIdent;
mainLicDescription += " => ";
dataToFile.header.licVersion = 10;
dataToFile.header.licType = licIdent.licIDType;
dataToFile.header.licDate = getLicDate(); //1692230400; //getLicDate(); //1692144000;// getLicDate();
mainLicDescription += dataToFile.header.licDescription1;
mainLicDescription += " [";
mainLicDescription += dataToFile.header.licDescription2;
mainLicDescription += "]";
if (licIdent.licIDType == cEzLic_p78ou3_IDType_EOVOSV)
{
if (generation == 1) // stará verze
{
dataToFile.header.licCount = 1;
dataToFile.items[0].licCount = 65535;
dataToFile.items[0].protoId = cEzLic_p78ou3_CheckLicNumberId_EOV1;
dataToFile.items[0].data1 = cEzLic_p78ou3_CheckLicNumber_EOV1;
}
else
{
dataToFile.header.licCount = 1;
dataToFile.items[1].licCount = 65535;
dataToFile.items[1].protoId = cEzLic_p78ou3_CheckLicNumberId_EOV1;
dataToFile.items[1].data1 = cEzLic_p78ou3_CheckLicNumber_EOV1;
}
}
unsigned char encrypted[10000] = {};
const int s = sizeof(dataToFile);
unsigned char byteArray[s] = {};
memcpy(byteArray, &dataToFile, sizeof(dataToFile));
dataToFile.crc = calculateCRC16(byteArray, s - sizeof(dataToFile.crc)); // 47535 | 884:38382
memcpy(byteArray, &dataToFile, sizeof(dataToFile));
int finalEncryptedLength = encrypt(byteArray, sizeof(dataToFile), this->cryptData.aesKey, this->cryptData.aesInitVector, encrypted);
if (licIdent.licPrefixType == cEzLic_p78ou3_LicPrefixType_ELC1) // typ1 = pouze zasifrovani dat
{
freeDataSize = sizeof(dataMainToFileELC1); // melo by byt 92
if (1) // EzLic_p78ou3_CryptoData.aesRetVal > 0 crypto
{
dataMainToFileELC1.prefix = 0x31434C45;
getCharsFromString(mainLicDescription, dataMainToFileELC1.licHeader.description);
dataMainToFileELC1.licHeader.sizeData = finalEncryptedLength; // sizeof(dataToFile); // 884;
dataMainToFileELC1.licHeader.licType = licIdent.licIDType;
dataMainToFileELC1.licHeader.licSubType = licIdent.licHeaderType << 8 | licIdent.licDataType;
}
}
const int dataMainLength = sizeof(dataMainToFileELC1);
const int dataToFileLength = sizeof(dataToFile);
const int dataEncryptedLength = finalEncryptedLength;
const int totalLength = dataMainLength + dataToFileLength;
const int totalEncryptedLength = dataMainLength + finalEncryptedLength;
unsigned char bdataMainToFileELC1[dataMainLength] = {};
memcpy(bdataMainToFileELC1, &dataMainToFileELC1, dataMainLength);
unsigned char bdataToFile[dataToFileLength] = {};
memcpy(bdataToFile, &dataToFile, dataToFileLength);
unsigned char totalEncryptedArray[totalEncryptedLength] = {};
for (int i = 0; i < dataMainLength; i++)
totalEncryptedArray[i] = bdataMainToFileELC1[i];
for (int i = 0; i < finalEncryptedLength; i++)
totalEncryptedArray[i + dataMainLength] = encrypted[i];
// char chFileName[licenseFileName.length()];
char licFileNameToSave[licenseFileName.length()] = {};
getCharsFromString(licenseFileName, licFileNameToSave);
int totalFileSize = sizeof(totalEncryptedArray);
if (binaryGeneration == BinaryGenerationType::File)
{
FILE *fileLicence = fopen(licFileNameToSave, "wb");
if (fileLicence)
{
size_t r1 = fwrite(&totalEncryptedArray, sizeof(totalEncryptedArray), 1, fileLicence);
//printf("License binary saved.\n");
fclose(fileLicence);
cout << licFileNameToSave << endl;
return true;
}
}
else
{
//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;
// string decodedBase64 = base64_decode_ai(base64Coded);
// std::ofstream outputFile("outputLicence.txt", std::ios::out | std::ios::binary);
// if (outputFile.is_open())
// {
// outputFile << decodedBase64;
// outputFile.close();
// std::cout << "File written successfully." << std::endl;
// }
// else { std::cerr << "Unable to open the file." << std::endl; }
return true;
// //file testing
// std::string filename = "source.txt ";
// std::string content;
// std::ifstream inputFile(filename);
// if (inputFile.is_open())
// {
// content.assign((std::istreambuf_iterator<char>(inputFile)), (std::istreambuf_iterator<char>()));
// inputFile.close();
// std::cout << "File content:\n" << content << std::endl;
// }
// else
// {
// std::cerr << "Unable to open the file." << std::endl;
// }
// std::ofstream outputFile("output.txt");
// if (outputFile.is_open())
// {
// string codedBase = base64_decode_ai(content);
// outputFile << "Velikost souboru orig souboru: " << codedBase.length() << "\n" << codedBase;
// outputFile.close();
// std::cout << "File written successfully." << std::endl;
// }
// else { std::cerr << "Unable to open the file." << std::endl; }
}
}
}
return false;
}
bool PlcLicence::ReadLicence(const char *dataFileName, WORD licType, BYTE licPostfix, char *cid, char *csd)
{
FILE *licenceFile;
char ch;
long lSize;
size_t result;
licenceFile = fopen(dataFileName, "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");
exit(EXIT_FAILURE);
}
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, cEzLic_p78ou3_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 << "\n";
return true;
}

282
src/ReadLicence.cpp Normal file
View File

@@ -0,0 +1,282 @@
#include "licenceReader.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
/// @brief hlavní funkce
/// @param argc
/// @param argv parametry pro generování licence
/// @return
int main()
{
// buffer,850client,104client, 104server, web
// kouknout na unikatní klíc pro linux (native uid, i openssl neco má)
try
{
InitStructure initStructure = {};
initStructure.licenceType = (int)LicenceType::DRT;
initStructure.licenceVersion = 1;
initStructure.licenceIndex = 0;
initStructure.licenceFilePath = ""; //c://_projects//sd_gen//output//"; // cesta k licenčnímu souboru
// initStructure.compatibility = 0; v případě kompatibility 0 či nezadané je výstup defaultní.
// pro ELC 1 LicenceELC1Info je to isValid, pro ELC 2 strukura { int protocolId = -1; int dataPointsCount = 0; }
initStructure.cid_csd_filePath = ""; // cesta k cidu/csd pro načtení a kontrolu licence
initStructure.uid_filePath = ""; // cesta k souboru machine-id. (/etc/machine-id), takze by mělo být /etc/.
//verze původní ELC 1, zatím zůstává staré řešení
LicenceReader licenceReaderELC1{};
if (licenceReaderELC1.initread(1, initStructure)) // iniciacni nacteni
{
LicenceELC1Info info; // struktura pro ELC1. Nemá tam asi nic jiného smysl nez true/false
if (licenceReaderELC1.getLicenceInfo(&info))
{
if (info.isValid)
cout << "Platna licence ELC1 \n";
else
cout << "Neplatna licence ELC1\n";
}
else
cout << "CHYBA: " << licenceReaderELC1.error.message;
}
else
{
cout << "CHYBA: " << licenceReaderELC1.error.message;
}
// verze ELC 2 pro jeden protokol
LicenceReader licenceReaderELC2{};
if (licenceReaderELC2.initread(2, initStructure)) // iniciacni nacteni
{
// v případě kompatibility 0, či nezadané výstup nativně je defaultní.
// v případně nenulové kompatibility, třeba 1, přidáme číslo kompatibility.
// Tedy pro ELC1 to bude LicenceELC1_1, pro ELC LicenceELC2_1
LicenceELC2Item info; // podle ELC a kompatibility určit strukuru (LicenceInfo11, LicenceInfo21, LicenceInfo31)
// if ()
int protocolId = 4;
// ukazka dat SD karty
cout << "SD přečteno: " << licenceReaderELC2.sdCardInfo.isLoaded << "\n";
cout << "Card size: " << licenceReaderELC2.sdCardInfo.cardSize << "\n";
cout << "serial: " << licenceReaderELC2.sdCardInfo.serialNumber << "\n";
cout << "date: " << licenceReaderELC2.sdCardInfo.date << "\n";
cout << "name: " << licenceReaderELC2.sdCardInfo.name << "\n";
cout << "oemID: " << licenceReaderELC2.sdCardInfo.oemID << "\n";
cout << "název licenčního souboru: " << licenceReaderELC2.licInfo.licenceFileName << "\n";
cout << "cesta k licenčnímu souboru: " << licenceReaderELC2.licInfo.licenceFilePath << "\n";
// if (initStructure.compatibility == 1) //ukazka kompatibilita 1
// {
// LicenceELC2Item_1 info; //jiná struktura, zbytek stejný
// if (licenceReaderELC2.getLicenceItemInfo(protocolId, &info))
// {
// cout << "Pocet licencních bodu pro " << info.protocolId << ": " << info.dataPointsCount << std::endl;
// }
//...........
// }
if (licenceReaderELC2.getLicenceItemInfo(protocolId, &info))
{
cout << "Pocet licencních bodu pro " << info.protocolId << ": " << info.dataPointsCount << std::endl;
}
else
cout << "Tento protokol nemá body";
}
else
{
cout << "CHYBA: " << licenceReaderELC2.error.message;
}
//---------------------------------------- ELC3 ----------------------------------------------------------
//verze ELC 3 pro jeden protokol. Oproti ELC2 je potřeba přidat cestu k uid/machine-id v initStructure
LicenceReader licenceReaderELC3{};
if (licenceReaderELC3.initread(3, initStructure)) // iniciacni nacteni
{
LicenceELC3Item info; // podle ELC a kompatibility určit strukuru (LicenceInfo1, LicenceInfo2, LicenceInfo3)
// if ()
int protocolId = 7;
if (licenceReaderELC3.getLicenceItemInfo(protocolId, &info))
{
cout << "Pocet licencních bodu pro " << info.protocolId << ": " << info.dataPointsCount << std::endl;
}
else
cout << "Tento protokol nemá body";
}
else
{
cout << "CHYBA: " << licenceReaderELC3.error.message;
}
//---------------------------------------- ELC3 ----------------------------------------------------------
// verze ELC 2 kompletní načtení
/*
LicenceReader licenceReaderCompleteELC2{};
if (licenceReaderCompleteELC2.init(2, initStructure)) // iniciacni nacteni
{
LicenceELC2Info info;
int protocolId = 2;
if (licenceReaderCompleteELC2.getLicenceInfo(&info))
{
if (info.licences.count(protocolId) > 0)
cout << "Pocet bodu z vectoru pro protokol : " << protocolId << ": " << info.licences.at(protocolId) << "\n";
else
cout << "Pro tento protokol nejsou definovay licencni body\n";
cout << "Vypis vsech licencnich bodu: " << endl;
// for (const auto &pair : info.licences)
// {
// std::cout << "<" << pair.first << ", " << pair.second << ">" << endl;
// }
}
else
cout << "CHYBA: " << licenceReaderCompleteELC2.error.message;
}
else
{
cout << "CHYBA: " << licenceReaderCompleteELC2.error.message;
}
*/
}
catch (...)
{
cout << "Obecna chyba\n";
}
system("pause");
return SUCCES;
// verze původní ELC 1, zatím zůstává staré řešení
// LicenceReader licenceReaderELC1{};
// if (licenceReaderELC1.initread(1, initStructure)) // iniciacni nacteni
// {
// LicenceELC1Info info; // struktura pro ELC1. Nemá tam asi nic jiného smysl nez true/false
// if (licenceReaderELC1.getLicenceInfo(&info))
// {
// if (info.isValid)
// cout << "Platna licence ELC1 \n";
// else
// cout << "Neplatna licence ELC1\n";
// }
// else
// cout << "CHYBA: " << licenceReaderELC1.error.message;
// }
// else
// {
// cout << "CHYBA: " << licenceReaderELC1.error.message;
// }
// return SUCCES;
}
// buffer,web, 850client,104client, 104server,
//
/*
pt_Ez_interHW, // 0 - interni virtualni typ pro urceni licence na dany HW
pt_Ez_buffer, // 1 - datovy Buffer
pt_Ez_webs, // 2 - Ez www conectivity server
pt_Ez_dblogc, // 3 - Ez database log client
pt_Ez_sysinfoc, // 4 - Systemove informace systemu
pt_Ez_iec104c, // 5 - IEC-104 client
pt_Ez_iec104s, // 6 - IEC-104 server
pt_Ez_iec61850c, // 7 - IEC-61850 client
pt_Ez_iec61850s, // 8 - IEC-61850 server
pt_Ez_mdbipc, // 9 - Modbus IP client
pt_Ez_mdbips, // 10 - Modbus IP server
pt_Ez_mdbrtum, // 11 - Modbus RTU master
pt_Ez_mdbrtul, // 12 - Modbus RTU slave
pt_Ez_mdbasciim, // 13 - Modbus ASCII master
pt_Ez_mdbasciil, // 14 - Modbus ASCII slave
pt_Ez_gsmm, // 15 - GSM master
pt_Ez_gsml, // 16 - GSM slave
pt_Ez_iec101m, // 17 - IEC-101 master
pt_Ez_iec101l, // 18 - IEC-101 slave
pt_Ez_iec103m, // 19 - IEC-103 master
pt_Ext_snmpc, // 20 - SNMP client
pt_Ext_snmps, // 21 - SNMP server
pt_Ez_siadc09c, // 22 - ANSI/SIA DC-09 client
pt_Ez_honeywellgxyc, // 23 - Honeywell Galaxy smart client
pt_Ez_contactidm, // 24 - Ademco Contact ID - SIA DC-05 master
pt_Ez_litesm, // 25 - EPS Lites master
pt_Ez_epsnetmpcc, // 26 - Tecomat Epsnet MPC client
pt_Ez_epsnetmpcs, // 27 - Tecomat Epsnet MPC server
pt_Ez_epsnetmpcm, // 28 - Tecomat Epsnet MPC master
pt_Ez_epsnetmpcl, // 29 - Tecomat Epsnet MPC slave
pt_Ez_epsnetplc, // 30 - Tecomat Epsnet PLC
pt_Ez_amitdbnetipc, // 31 - AMiT DB-Net/IP client
pt_Ez_amitdbnetm, // 32 - AMiT DB-Net master
pt_Ez_fatekm, // 33 - Fatek master
pt_Ez_canm, // 34 - CAN master
pt_Ez_iec6205621m, // 35 - IEC 62056.21 master
pt_Ez_mbusm, // 36 - MBus master
pt_Ez_azddakm, // 37 - AZD DAK master
pt_Ez_rwaytechc, // 38 - RwayTech client (modbus IP)
pt_Ez_weinteksl, // 39 - Weintek touch screen server/slave (modbus protokol)
Pro index 0 (pt_Ez_interHW) jsou možné hodnoty (počet licenčních bodů):
#define EZ_HW_TECOMAT 1
#define EZ_HW_WAGO 2
#define EZ_HW_NATIVE_LINUX 3
#define EZ_HW_NATIVE_LINUX_DOCKER 4
#define EZ_HW_ARM64_LINUX 5
#define EZ_HW_ARM64_LINUX_DOCKER 6
Pro ostatní je uveden skutečný požadovaný počet licenčních bodů pro daný protokol.
U protokolů pt_Ez_buffer a pt_Ez_webs nastavovat defaultně EZ_PROTO_INFINITE = 4294967295
*/
/*
pt_Ez_interHW, // 0 - interni virtualni typ pro urceni licence na dany HW
pt_Ez_buffer, // 1 - datovy Buffer
pt_Ez_webs, // 2 - Ez www conectivity server
pt_Ez_dblogc, // 3 - Ez database log client
pt_Ez_mdbipc, // 4 - Modbus IP client
pt_Ez_mdbips, // 5 - Modbus IP server
pt_Ext_snmpc, // 6 - SNMP client
pt_Ext_snmps, // 7 - SNMP server
pt_Ez_iec104s, // 8 - IEC-104 server
pt_Ez_iec104c, // 9 - IEC-104 client
pt_Ez_sysinfoc, // 10 - Systemove informace systemu
pt_Ez_siadc09c, // 11 - ANSI/SIA DC-09 client
pt_Ez_honeywellgxyc, // 12 - Honeywell Galaxy smart client
pt_Ez_iec61850s, // 13 - IEC-61850 server
pt_Ez_iec61850c, // 14 - IEC-61850 client
pt_Ez_mdbrtum, // 15 - Modbus RTU master
pt_Ez_mdbrtul, // 16 - Modbus RTU slave
pt_Ez_mdbasciim, // 17 - Modbus ASCII master
pt_Ez_mdbasciil, // 18 - Modbus ASCII slave
pt_Ez_epsnetmpcc, // 19 - Tecomat Epsnet MPC client
pt_Ez_epsnetmpcs, // 20 - Tecomat Epsnet MPC server
pt_Ez_epsnetmpcl, // 21 - Tecomat Epsnet MPC slave
pt_Ez_epsnetmpcm, // 22 - Tecomat Epsnet MPC master
pt_Ez_epsnetplc, // 23 - Tecomat Epsnet PLC
pt_Ez_litesm, // 24 - EPS Lites master
pt_Ez_contactidm, // 25 - Ademco Contact ID - SIA DC-05 master
pt_Ez_amitdbnetipc, // 26 - AMiT DB-Net/IP client
pt_Ez_amitdbnetm, // 27 - AMiT DB-Net master
pt_Ez_fatekm, // 28 - Fatek master
pt_Ez_canm, // 29 - CAN master
pt_Ez_iec6205621m, // 30 - IEC 62056.21 master
pt_Ez_mbusm, // 31 - MBus master
pt_Ez_gsmm, // 32 - GSM master
pt_Ez_gsml, // 33 - GSM slave
pt_Ez_iec101m, // 34 - IEC-101 master
pt_Ez_iec101l, // 35 - IEC-101 slave
pt_Ez_iec103m, // 36 - IEC-103 master
pt_Ez_azddakm, // 37 - AZD DAK master
pt_Ez_rwaytechc, // 38 - RwayTech client (modbus IP)
pt_Ez_weinteksl, // 39 - Weintek touch screen server/slave (modbus protokol)
*/
#endif

103
src/_c++notes.txt Normal file
View File

@@ -0,0 +1,103 @@
--------------------------------------------------------------------------------------------------
It is often wise to check that a pointer argument that is supposed to point to something, actually
points to something:
int count_x(char p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-ter minated array of char (or to nothing)
{
if (p==nullptr) return 0;
int count = 0;
for (; p!=0; ++p)
if (p==x)
++count;
return count;
}
Note how we can move a pointer to point to the next element of an array using ++ and that we can
leave out the initializer in a for-statement if we dont need it.
The definition of count_x() assumes that the char is a C-style string, that is, that the pointer
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)
{
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
public:
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

5
src/cid Normal file
View File

@@ -0,0 +1,5 @@
9f54495344434954615ad803c50171bf
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

150
src/common/SDCard.cpp Normal file
View File

@@ -0,0 +1,150 @@
#include "SDCard.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
SDCard::SDCard()
{
}
SDCard::SDCard(const string cds_cid_Path)
{
this->filePath = cds_cid_Path;
if (getCIDFromFile() == false)
return;
if (getCSDFromFile() == false)
return;
this->isLoaded = SDCard::readSDCard();
}
SDCard::SDCard(string cid, string csd)
{
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();
}
bool SDCard::readSDCard()
{
BYTE cHexNibbleToNo[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < CID_LENGTH; i++)
this->cardData.CID_nibble[i] = (BYTE)cid[i];
for (int i = 0; i < cnibblescount / 2; i++)
{
this->cardData.CID[i] = cHexNibbleToNo[this->cardData.CID_nibble[2 * i]] << 4 | cHexNibbleToNo[this->cardData.CID_nibble[2 * i + 1]];
}
this->cardData.manufacturerID = this->cardData.CID[0];
this->cardData.oemID[0] = this->cardData.CID[1];
this->cardData.oemID[1] = this->cardData.CID[2];
this->cardData.name[0] = this->cardData.CID[3];
this->cardData.name[1] = this->cardData.CID[4];
this->cardData.name[2] = this->cardData.CID[5];
this->cardData.name[3] = this->cardData.CID[6];
this->cardData.name[4] = this->cardData.CID[7];
this->cardData.productRevision_hw = cHexNibbleToNo[this->cardData.CID[16]];
this->cardData.productRevision_sw = cHexNibbleToNo[this->cardData.CID[17]];
if (this->cardData.productRevision_sw < 10)
this->cardData.productRevision = (float)this->cardData.productRevision_hw + ((float)this->cardData.productRevision_sw * 0.1);
else
this->cardData.productRevision = (float)this->cardData.productRevision_hw + ((float)this->cardData.productRevision_sw * 0.01);
this->cardData.serialNumber = this->cardData.CID[9] << 24 | this->cardData.CID[10] << 16 | this->cardData.CID[11] << 8 | this->cardData.CID[12];
this->cardData.manufacturerDate_year = cHexNibbleToNo[this->cardData.CID_nibble[27]] * 10 + cHexNibbleToNo[this->cardData.CID_nibble[28]] + 2000;
this->cardData.manufacturerDate_month = cHexNibbleToNo[this->cardData.CID_nibble[29]];
this->cardData.date = to_string(this->cardData.manufacturerDate_month) + "/" + to_string(this->cardData.manufacturerDate_year);
//string date = cSDMonthStr1[this->sdData.manufacturerDate_month] + std::to_string(this->sdData.manufacturerDate_year);
// CSD
for (int i = 0; i < CSD_LENGTH; i++)
this->cardData.CSD_nibble[i] = (BYTE)csd[i];
for (int i = 0; i < cnibblescount / 2; i++)
{
this->cardData.CSD[i] = cHexNibbleToNo[this->cardData.CSD_nibble[2 * i]] << 4 | cHexNibbleToNo[this->cardData.CSD_nibble[2 * i + 1]];
}
if (this->cardData.CSD_nibble[0] == 0x34)
{
this->cardData.cardSize = this->cardData.CSD[7] << 16 | this->cardData.CSD[8] << 8 | this->cardData.CSD[9];
this->cardData.cardGSize = (this->cardData.cardSize + 1) / 2048;
}
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()
{
vector<char> content;
if (readFile(this->filePath + "cid", content) == false)
{
return false;
}
if (content.size() >= CID_LENGTH)
{
for (int i = 0; i < 32; i++)
this->cid[i] = content[i];
}
else
return false;
return true;
}
bool SDCard::getCSDFromFile()
{
vector<char> content;
if (readFile(this->filePath + "csd", content) == false)
{
return false;
}
if (content.size() >= CSD_LENGTH)
{
for (int i = 0; i < 32; i++)
this->csd[i] = content[i];
}
else
return false;
return true;
}
#endif

3
src/common/SDCard.d Normal file
View File

@@ -0,0 +1,3 @@
src/common/SDCard.o: src/common/SDCard.cpp include/common/SDCard.h \
include/common/utils.h include/common/licConnector.h \
include/common/lic_config.h

BIN
src/common/SDCard.o Normal file

Binary file not shown.

5
src/common/cid Normal file
View File

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

2
src/common/csd Normal file
View File

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

Binary file not shown.

37
src/common/licData.xml Normal file
View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8" ?>
<licence elc="2" xmlVersion="1" revision="1" compatibility="1">
<licenceType licenceVersion="1" licenceIndex="0">EOV_OSV</licenceType>
<plcType>WAGO</plcType>
<licenceName>Licence pro EOV_OSV</licenceName>
<station>eov.ceskatrebova.ddts.cz</station>
<distributor>eov2</distributor>
<project>Projekt XXX stanice YYY</project>
<items>
<item>
<name>Položka licence 1</name>
<protoId>111</protoId>
<dataPointsCount>100</dataPointsCount>
</item>
<item>
<name>Položka licence 2</name>
<protoId>222</protoId>
<dataPointsCount>200</dataPointsCount>
</item>
<item>
<name>Položka licence 3</name>
<protoId>333</protoId>
<dataPointsCount>300</dataPointsCount>
</item>
<item>
<name>Položka licence 3</name>
<protoId>444</protoId>
<dataPointsCount>1600</dataPointsCount>
</item>
<item>
<name>Položka licence 4</name>
<protoId>555</protoId>
<dataPointsCount>1999</dataPointsCount>
</item>
</items>
</licence>

220
src/common/licenceELC1.cpp Normal file
View File

@@ -0,0 +1,220 @@
#include "licenceELC1.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#define CID_LENGTH 32
#define CSD_LENGTH 32
const std::string cEzLic_p78ou3_sdinfofilepath = "/sys/block/mmcblk0/device/";
const std::string cEzLic_p78ou3_licencfilepath_f21 = "/mnt/mmc/ez_sys/licence/";
const std::string cEzLic_p78ou3_licencfilepath_f17 = "/home/admin/ez/licence/";
const string cEzLic_p78ou3_licencfilepath_f10 = "/root/ez_sys/licence/";
const WORD maxDataToFile = 10000; // velikost datoveho bufferu pro ulozeni dat licence
const BYTE licMaxCount = 100;
const DWORD cEzLic_p78ou3_CheckLicNumber_ERR = 0xFFFFFFFF; // 16#FFFFFFFF; // chybna identifikace licence
const DWORD cEzLic_p78ou3_CheckLicNumber_EOV1 = 3781234965; // cislo pro overeni licence EOV, OSV verze 1
const BYTE cEzLic_p78ou3_CheckLicNumberId_ERR = 0; // id licence pro neidentifikovanou licenci
const BYTE cEzLic_p78ou3_CheckLicNumberId_EOV1 = 1; // id licence pro EOV, OSV verze 1
const BYTE cEzLic_p78ou3_MaxCheckLicNumberId = cEzLic_p78ou3_CheckLicNumberId_EOV1; // pocet identifikatoru licenci
const DWORD cEzLic_p78ou3_CheckLicNumber[] = {cEzLic_p78ou3_CheckLicNumber_ERR, cEzLic_p78ou3_CheckLicNumber_EOV1};
const WORD cEzLic_p78ou3_LicPrefixType_ELC1 = 1; // prefix typ1 = pouze zasifrovani dat
const WORD cEzLic_p78ou3_HeaderType_10 = 10; // hlavicka kriptovane casti verze 1.0
const WORD cEzLic_p78ou3_DataType_10 = 10; // data licence verze 1.0
const WORD cEzLic_p78ou3_SubType_10_10 = 0x0A0A; // subtype - verze hlavicky + verze data -> cEzLic_p78ou3_HeaderType_XX * 256 + cEzLic_p78ou3_DataType_XX
// ID aplikace
const WORD cEzLic_p78ou3_IDType_DDTS = 1; // aplikace DDTS
const WORD cEzLic_p78ou3_IDType_EOVOSV = 2; // aplikace EOV-OSV
const WORD cEzLic_p78ou3_IDType_DRT = 3; // aplikace DRT
// std::string cEzLic_p78ou3_IDTypeStrData11[] = {"neznamo", "DDTS", "EOV-OSV", "DRT"};
const BYTE cnibblescount1 = 32;
std::string cSDMonthStr1[] = {"-", "I.", "II.", "III.", "IV.", "V.", "VI.", "VII.", "VIII.", "IX.", "X.", "XI.", "XII.", "-", "-", "-"};
BYTE cHexNibble_to_No1[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const string eoseovLicenceType = "EOV_OSV";
LicenceELC1::LicenceELC1() {}
LicenceELC1::~LicenceELC1() {}
LicenceELC1::LicenceELC1(LicenceIdentification &licIdentification) : lIdentification(licIdentification)
{
}
bool LicenceELC1::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_No1[this->sdData.CID_nibble[2 * i]] << 4 | cHexNibble_to_No1[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_No1[this->sdData.CID[16]];
this->sdData.productRevision_sw = cHexNibble_to_No1[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_No1[this->sdData.CID_nibble[27]] * 10 + cHexNibble_to_No1[this->sdData.CID_nibble[28]] + 2000;
this->sdData.manufacturerDate_month = cHexNibble_to_No1[this->sdData.CID_nibble[29]];
string date = cSDMonthStr1[this->sdData.manufacturerDate_month] + std::to_string(this->sdData.manufacturerDate_year);
for (unsigned i = 0; i < date.length(); i++)
this->sdData.manufacturerDate[i] = date[i];
// CSD
for (unsigned int i = 0; i < CSD_LENGTH; i++) this->sdData.CSD_nibble[i] = (BYTE)csd[i];
for (unsigned int i = 0; i < cnibblescount / 2; i++)
{
this->sdData.CSD[i] = cHexNibble_to_No1[this->sdData.CSD_nibble[2 * i]] << 4 | cHexNibble_to_No1[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;
}
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];
return (int)this->sdData.CID[15] == (int)((sdCrc << 1) | 1);
}
void LicenceELC1::initCrypto()
{
if (this->licType == cEzLic_p78ou3_IDType_EOVOSV)
{
this->cryptData.aesInitVector[0] = this->sdData.CID[10];
this->cryptData.aesInitVector[1] = this->sdData.CID[12];
this->cryptData.aesInitVector[2] = this->sdData.CID[11];
this->cryptData.aesInitVector[3] = this->sdData.CID[9];
this->cryptData.aesInitVector[4] = this->sdData.CID_nibble[22] - 15;
this->cryptData.aesInitVector[5] = this->sdData.CID_nibble[24] - 15;
this->cryptData.aesInitVector[6] = this->sdData.CID_nibble[25] - 15;
this->cryptData.aesInitVector[7] = this->sdData.CID_nibble[21] - 15;
memcpy(&this->cryptData.aesInitVector[8], &this->cryptData.aesInitVector[0], 8);
this->cryptData.aesKey[0] = this->sdData.CID[12];
this->cryptData.aesKey[1] = this->sdData.CID_nibble[23] - 15;
this->cryptData.aesKey[2] = this->sdData.CID_nibble[25] - 15;
this->cryptData.aesKey[3] = this->sdData.CID[11];
this->cryptData.aesKey[4] = this->sdData.CID[9];
this->cryptData.aesKey[5] = this->sdData.CID_nibble[21] - 15;
this->cryptData.aesKey[6] = 97 + this->sdData.CID[9] % 25;
this->cryptData.aesKey[7] = this->sdData.CID_nibble[22] - 15;
memcpy(&this->cryptData.aesKey[8], &this->cryptData.aesKey[0], 8);
memcpy(&this->cryptData.aesKey[16], &this->cryptData.aesKey[6], 8);
memcpy(&this->cryptData.aesKey[24], &this->cryptData.aesKey[12], 8);
}
}
string LicenceELC1::getLicenceName()
{
string result = "";
char prefixChar = 97;
int licIndex = lIdentification.licenceIndex;
// natvrdo, stará ELC
result = "ezlic_eovosv" + to_string(licIndex) + "_";
result += prefixChar + (this->sdCard.cardData.CID[12] % 25);
result += prefixChar + (this->sdCard.cardData.CID[10] % 25);
result += prefixChar + (this->sdCard.cardData.CID_nibble[22] % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[23] * 2) % 25);
result += prefixChar + (this->sdCard.cardData.CID_nibble[24] % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[25] * 3) % 25);
result += prefixChar + (this->sdCard.cardData.CID[9] % 25);
result += prefixChar + (this->sdCard.cardData.CID[11] % 25);
result += prefixChar + (this->sdCard.cardData.CID[2] % 25);
result += prefixChar + (this->sdCard.cardData.CID[1] % 25);
result += prefixChar + (this->sdCard.cardData.CID[3] % 25);
result += ".lic";
return result;
}
/// @brief get proper licencename
/// @param licPostfix
/// @return
string LicenceELC1::getLicenceName(BYTE licPostfix)
{
string result = "";
char prefixChar = 97;
if (licType == PlcLicenceType::LicenceOther)
{
result = "ezlic_";
result += prefixChar + (this->sdData.CID[12] % 25);
result += prefixChar + (this->sdData.CID[10] % 25);
result += prefixChar + (this->sdData.CID_nibble[22] % 25);
result += prefixChar + ((this->sdData.CID_nibble[23] * 2) % 25);
result += prefixChar + (this->sdData.CID_nibble[24] % 25);
result += prefixChar + ((this->sdData.CID_nibble[25] * 3) % 25);
result += prefixChar + (this->sdData.CID[9] % 25);
result += prefixChar + (this->sdData.CID[11] % 25);
result += prefixChar + (this->sdData.CID[2] % 25);
result += prefixChar + (this->sdData.CID[1] % 25);
result += prefixChar + (this->sdData.CID[3] % 25);
result += ".lic";
}
else
{
result = "ezlic_eovosv" + to_string(licPostfix) + "_";
result += prefixChar + (this->sdData.CID[12] % 25);
result += prefixChar + (this->sdData.CID[10] % 25);
result += prefixChar + (this->sdData.CID_nibble[22] % 25);
result += prefixChar + ((this->sdData.CID_nibble[23] * 2) % 25);
result += prefixChar + (this->sdData.CID_nibble[24] % 25);
result += prefixChar + ((this->sdData.CID_nibble[25] * 3) % 25);
result += prefixChar + (this->sdData.CID[9] % 25);
result += prefixChar + (this->sdData.CID[11] % 25);
result += prefixChar + (this->sdData.CID[2] % 25);
result += prefixChar + (this->sdData.CID[1] % 25);
result += prefixChar + (this->sdData.CID[3] % 25);
result += ".lic";
}
return result;
}
#endif

4
src/common/licenceELC1.d Normal file
View File

@@ -0,0 +1,4 @@
src/common/licenceELC1.o: src/common/licenceELC1.cpp \
include/common/licenceELC1.h include/common/utils.h \
include/common/licConnector.h include/common/lic_config.h \
include/common/licenceCommon.h include/common/SDCard.h

BIN
src/common/licenceELC1.o Normal file

Binary file not shown.

184
src/common/licenceELC2.cpp Normal file
View File

@@ -0,0 +1,184 @@
#include "licenceELC2.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
LicenceELC2::LicenceELC2() {}
LicenceELC2::~LicenceELC2() {}
LicenceELC2::LicenceELC2(LicenceIdentification &licIdentification) : lIdentification(licIdentification)
{
}
/// @brief get proper licencename
/// @param licPostfix
/// @return
string LicenceELC2::getLicenceName()
{
string result = "";
char prefixChar = 97;
int licType = (int)lIdentification.licLicenceType;
int lVersion = lIdentification.licenceVersion;
unordered_map<int, string> baseString;
baseString.insert(std::pair<int, string>((int)LicenceType::EOS_EOV, "ezlic_eovosv"));
baseString.insert(std::pair<int, string>((int)LicenceType::DDTS, "ezlic_ddts"));
baseString.insert(std::pair<int, string>((int)LicenceType::DRT, "ezlic_drt"));
struct Index
{
int index[11];
};
std::unordered_map<int, Index> indexes;
Index indexes1 = {7, 16, 20, 23, 18, 4, 9, 11, 6, 9, 13};
Index indexes2 = {12, 10, 22, 23, 24, 25, 9, 11, 2, 1, 3}; // puvodní indexy
Index indexes3 = {8, 13, 11, 9, 7, 11, 10, 13, 5, 20, 19};
indexes.insert(std::pair<int, Index>(1, indexes1));
indexes.insert(std::pair<int, Index>(2, indexes2));
indexes.insert(std::pair<int, Index>(3, indexes3));
result = baseString.at(licType) + to_string(lIdentification.licenceIndex) + "_";
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[0]] + (lIdentification.licenceIndex * 11)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[1]] + (lIdentification.licenceIndex * 39)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[2]] + (lIdentification.licenceIndex * 1)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[3]] * 2) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[4]] + (lIdentification.licenceIndex * 5)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID_nibble[indexes.at(lVersion).index[5]] * 3) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[6]] + (lIdentification.licenceIndex * 52)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[7]] + (lIdentification.licenceIndex * 34)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[8]] + (lIdentification.licenceIndex * 21)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[9]] + (lIdentification.licenceIndex * 47)) % 25);
result += prefixChar + ((this->sdCard.cardData.CID[indexes.at(lVersion).index[10]] + (lIdentification.licenceIndex * 7)) % 25);
result += ".lic";
return result;
}
vector<unsigned char> LicenceELC2::cryptPrivateContent(const std::vector<unsigned char> &content)
{
// BYTE initVector[15] = {}; old funkční s 15, předěláme to do 16 pro test
// BYTE aesKey[32] = {};
BYTE initVector[CRYPT_INIT_VECTOR_SIZE] = {0};
BYTE aesKey[CRYPT_INIT_KEY_SIZE] = {0};
LicenceELC2::initVector(initVector, aesKey);
unsigned char encrypted[10000] = {};
const unsigned char *plainTextArray = content.data();
int finalEncryptedLength = encrypt(plainTextArray, content.size(), aesKey, initVector, encrypted);
if (finalEncryptedLength <= 0)
throw LicenceException((int)GeneralError::EncryptError, "Chyba při kryptování.");
std::vector<unsigned char> result(encrypted, encrypted + finalEncryptedLength);
return result;
}
vector<unsigned char> LicenceELC2::decryptPrivateContent(const std::vector<unsigned char> &content)
{
BYTE initVector[CRYPT_INIT_VECTOR_SIZE] = {0};
BYTE aesKey[CRYPT_INIT_KEY_SIZE] = {0};
LicenceELC2::initVector(initVector, aesKey);
const unsigned char *encryptedData = content.data();
unsigned char decrypted[10000] = {};
// cout << "\n --- zašifrovaná data přímo z decrypt metody:" << content.size() << "--- \n";
// for (int i = 0; i < (int)content.size(); i++)
// {
// cout << (int)encryptedData[i] << "-";
// }
// cout << "---\n\n";
int decrypted_len = decrypt(encryptedData, content.size(), aesKey, initVector, decrypted);
if (decrypted_len <= 0)
throw LicenceException((int)GeneralError::DecryptError, "Chyba při dekryptování.");
vector<unsigned char> res{};
for (int i = 0; i < decrypted_len; i++)
{
res.push_back(decrypted[i]);
}
// cout << "\n --- dešifrovaná data přímo z decrypt metody:" << content.size() << "--- \n";
// for (int i = 0; i < decrypted_len; i++)
// {
// cout << (int)decrypted[i] << "-";
// }
// cout << "---\n\n";
return res;
// std::vector<unsigned char> result(decrypted, decrypted + decrypted_len);
// return result;
}
void LicenceELC2::initVector(BYTE *iVector, BYTE *key)
{
CryptInitVector vec1 = {this->sdCard.cardData.CID[10],
this->sdCard.cardData.CID[12],
this->sdCard.cardData.CID[11],
this->sdCard.cardData.CID[9],
this->sdCard.cardData.CID_nibble[22] - 15,
this->sdCard.cardData.CID_nibble[24] - 15,
this->sdCard.cardData.CID_nibble[25] - 15,
this->sdCard.cardData.CID_nibble[21] - 15,
9, 10, 11, 12, 13, 14, 15, 16};
CryptInitVector vec2 = {5, 1, 3, this->sdCard.cardData.CID[9], 4, 12, 13, 17, 9, this->sdCard.cardData.CID_nibble[24]-15, 2, 23, 17, 13, 4, 3};
CryptInitVector vec3 = {2, 7, 1, this->sdCard.cardData.CID[6], 8, 13, 16, 6, 4, this->sdCard.cardData.CID_nibble[20]-15, 8, 7, 2, 14, 15, 21};
std::unordered_map<int, CryptInitVector> vectors;
vectors.insert(std::pair<int, CryptInitVector>(1, vec1));
vectors.insert(std::pair<int, CryptInitVector>(2, vec2));
vectors.insert(std::pair<int, CryptInitVector>(3, vec3));
CryptAesKey key1 = {this->sdCard.cardData.CID[12],
this->sdCard.cardData.CID[23] - 15,
this->sdCard.cardData.CID[25] - 15,
this->sdCard.cardData.CID[11],
this->sdCard.cardData.CID[9],
this->sdCard.cardData.CID_nibble[21],
this->sdCard.cardData.CID[9] % 25,
this->sdCard.cardData.CID_nibble[22] - 15,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
CryptAesKey key2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
CryptAesKey key3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
std::unordered_map<int, CryptAesKey> keys;
keys.insert(std::pair<int, CryptAesKey>(1, key1));
keys.insert(std::pair<int, CryptAesKey>(2, key2));
keys.insert(std::pair<int, CryptAesKey>(3, key3));
int lVersion = lIdentification.licenceVersion;
iVector[0] = vectors.at(lVersion).vec[0];
iVector[1] = vectors.at(lVersion).vec[1];
iVector[2] = vectors.at(lVersion).vec[2];
iVector[3] = vectors.at(lVersion).vec[3];
iVector[4] = vectors.at(lVersion).vec[4];
iVector[5] = vectors.at(lVersion).vec[5];
iVector[6] = vectors.at(lVersion).vec[6];
iVector[7] = vectors.at(lVersion).vec[7];
memcpy(&iVector[8], &iVector[0], 8);
key[0] = keys.at(lVersion).key[0];
key[1] = keys.at(lVersion).key[1];
key[2] = keys.at(lVersion).key[2];
key[3] = keys.at(lVersion).key[3];
key[4] = keys.at(lVersion).key[4];
key[5] = keys.at(lVersion).key[5];
key[6] = keys.at(lVersion).key[6];
key[7] = keys.at(lVersion).key[7];
memcpy(&key[8], &key[0], 8);
memcpy(&key[16], &key[6], 8);
memcpy(&key[24], &key[12], 8);
}
#endif

4
src/common/licenceELC2.d Normal file
View File

@@ -0,0 +1,4 @@
src/common/licenceELC2.o: src/common/licenceELC2.cpp \
include/common/licenceELC2.h include/common/utils.h \
include/common/licConnector.h include/common/lic_config.h \
include/common/licenceCommon.h include/common/SDCard.h

BIN
src/common/licenceELC2.o Normal file

Binary file not shown.

177
src/common/licenceELC3.cpp Normal file
View File

@@ -0,0 +1,177 @@
#include "licenceELC3.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
LicenceELC3::LicenceELC3() {}
LicenceELC3::~LicenceELC3() {}
LicenceELC3::LicenceELC3(LicenceIdentification &licIdentification) : lIdentification(licIdentification)
{
}
/// @brief get proper licencename
/// @param licPostfix
/// @return
string LicenceELC3::getLicenceName()
{
BYTE uidb[UID_LENGTH] = {};
for (unsigned int i = 0; i < this->uid.length(); i++) uidb[i] = uid[i];
string result = "";
char prefixChar = 97;
int licType = (int)lIdentification.licLicenceType;
int lVersion = lIdentification.licenceVersion;
unordered_map<int, string> baseString;
baseString.insert(std::pair<int, string>((int)LicenceType::EOS_EOV, "ezlic_eovosv"));
baseString.insert(std::pair<int, string>((int)LicenceType::DDTS, "ezlic_ddts"));
baseString.insert(std::pair<int, string>((int)LicenceType::DRT, "ezlic_drt"));
struct Index
{
int index[11];
};
std::unordered_map<int, Index> indexes;
Index indexes1 = {7, 16, 20, 23, 18, 4, 9, 11, 6, 9, 13};
Index indexes2 = {12, 10, 22, 23, 24, 25, 9, 11, 2, 1, 3}; // puvodní indexy
Index indexes3 = {8, 13, 11, 9, 7, 11, 10, 13, 5, 20, 19};
indexes.insert(std::pair<int, Index>(1, indexes1));
indexes.insert(std::pair<int, Index>(2, indexes2));
indexes.insert(std::pair<int, Index>(3, indexes3));
result = baseString.at(licType) + to_string(lIdentification.licenceIndex) + "_";
result += prefixChar + ((uidb[indexes.at(lVersion).index[0]] + (lIdentification.licenceIndex * 11)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[1]] + (lIdentification.licenceIndex * 39)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[2]] + (lIdentification.licenceIndex * 1)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[3]] * 2) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[4]] + (lIdentification.licenceIndex * 5)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[5]] * 3) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[6]] + (lIdentification.licenceIndex * 52)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[7]] + (lIdentification.licenceIndex * 34)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[8]] + (lIdentification.licenceIndex * 21)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[9]] + (lIdentification.licenceIndex * 47)) % 25);
result += prefixChar + ((uidb[indexes.at(lVersion).index[10]] + (lIdentification.licenceIndex * 7)) % 25);
result += ".lic";
return result;
}
vector<unsigned char> LicenceELC3::cryptPrivateContent(const std::vector<unsigned char> &content)
{
BYTE initVector[CRYPT_INIT_VECTOR_SIZE] = {0};
BYTE aesKey[CRYPT_INIT_KEY_SIZE] = {0};
LicenceELC3::initVector(initVector, aesKey);
unsigned char encrypted[10000] = {};
const unsigned char *plainTextArray = content.data();
int finalEncryptedLength = encrypt(plainTextArray, content.size(), aesKey, initVector, encrypted);
if (finalEncryptedLength <= 0)
throw LicenceException((int)GeneralError::EncryptError, "Chyba při kryptování.");
std::vector<unsigned char> result(encrypted, encrypted + finalEncryptedLength);
return result;
}
vector<unsigned char> LicenceELC3::decryptPrivateContent(const std::vector<unsigned char> &content)
{
BYTE initVector[CRYPT_INIT_VECTOR_SIZE] = {0};
BYTE aesKey[CRYPT_INIT_KEY_SIZE] = {0};
LicenceELC3::initVector(initVector, aesKey);
const unsigned char *encryptedData = content.data();
unsigned char decrypted[10000] = {};
int decrypted_len = decrypt(encryptedData, content.size(), aesKey, initVector, decrypted);
if (decrypted_len <= 0)
throw LicenceException((int)GeneralError::DecryptError, "Chyba při dekryptování.");
vector<unsigned char> res{};
for (int i = 0; i < decrypted_len; i++)
{
res.push_back(decrypted[i]);
}
return res;
}
void LicenceELC3::initVector(BYTE *iVector, BYTE *key)
{
BYTE uidb[UID_LENGTH] = {};
for (unsigned int i = 0; i < this->uid.length(); i++) uidb[i] = uid[i];
CryptInitVector vec1 = {uidb[10],
uidb[12],
uidb[11],
uidb[9],
uidb[22]-6,
uidb[24]-4,
uidb[25]-13,
uidb[21]-9,
9, 10, 11, 12, 13, 14, 15, 16};
CryptInitVector vec2 = {5, 1, 3, uidb[9], 4, 12, 13, 17, 9, uidb[24]-15, 2, 23, 17, 13, 4, 3};
CryptInitVector vec3 = {2, 7, 1, uidb[6], 8, 13, 16, 6, 4, uidb[20]-15, 8, 7, 2, 14, 15, 21};
std::unordered_map<int, CryptInitVector> vectors;
vectors.insert(std::pair<int, CryptInitVector>(1, vec1));
vectors.insert(std::pair<int, CryptInitVector>(2, vec2));
vectors.insert(std::pair<int, CryptInitVector>(3, vec3));
CryptAesKey key1 = {uidb[12],
uidb[23] - 15,
uidb[25] - 15,
uidb[11],
uidb[9],
uidb[21],
uidb[9] % 25,
uidb[22] - 15,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
CryptAesKey key2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
CryptAesKey key3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
std::unordered_map<int, CryptAesKey> keys;
keys.insert(std::pair<int, CryptAesKey>(1, key1));
keys.insert(std::pair<int, CryptAesKey>(2, key2));
keys.insert(std::pair<int, CryptAesKey>(3, key3));
int lVersion = lIdentification.licenceVersion;
iVector[0] = vectors.at(lVersion).vec[0];
iVector[1] = vectors.at(lVersion).vec[1];
iVector[2] = vectors.at(lVersion).vec[2];
iVector[3] = vectors.at(lVersion).vec[3];
iVector[4] = vectors.at(lVersion).vec[4];
iVector[5] = vectors.at(lVersion).vec[5];
iVector[6] = vectors.at(lVersion).vec[6];
iVector[7] = vectors.at(lVersion).vec[7];
memcpy(&iVector[8], &iVector[0], 8);
key[0] = keys.at(lVersion).key[0];
key[1] = keys.at(lVersion).key[1];
key[2] = keys.at(lVersion).key[2];
key[3] = keys.at(lVersion).key[3];
key[4] = keys.at(lVersion).key[4];
key[5] = keys.at(lVersion).key[5];
key[6] = keys.at(lVersion).key[6];
key[7] = keys.at(lVersion).key[7];
memcpy(&key[8], &key[0], 8);
memcpy(&key[16], &key[6], 8);
memcpy(&key[24], &key[12], 8);
}
#endif

4
src/common/licenceELC3.d Normal file
View File

@@ -0,0 +1,4 @@
src/common/licenceELC3.o: src/common/licenceELC3.cpp \
include/common/licenceELC3.h include/common/utils.h \
include/common/licConnector.h include/common/lic_config.h \
include/common/licenceCommon.h

BIN
src/common/licenceELC3.o Normal file

Binary file not shown.

488
src/common/utils.cpp Normal file
View File

@@ -0,0 +1,488 @@
#include "utils.h"
#ifndef EZ_APPLICATION_LICENCE_DISABLE
#include <openssl/conf.h>
#include <openssl/ssl.h> /* core library */
using namespace std;
using namespace std;
const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const char base64_url_alphabet[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'};
void getCharsFromString(string &source, char *charArray, size_t length)
{
for (size_t i = 0; i < length; i++)
{
charArray[i] = source[i];
}
}
void getCharsFromString(string source, char *charArray)
{
size_t length = source.length();
for (size_t i = 0; i < length; i++)
{
charArray[i] = source[i];
}
}
std::string right(const std::string &sourceString, size_t numChars)
{
if (numChars >= sourceString.size())
{
return sourceString; // If numChars is greater or equal to the string size, return the whole string.
}
return sourceString.substr(sourceString.size() - numChars);
}
uint16_t calculateCRC16(const uint8_t *data, size_t length)
{
const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
uint16_t crc = 0xFFFF; // Initial value
for (size_t i = 0; i < length; i++)
{
crc ^= data[i]; // XOR with the current data byte
for (int j = 0; j < 8; j++)
{
if (crc & 0x0001)
{
crc = (crc >> 1) ^ polynomial;
}
else
{
crc = crc >> 1;
}
}
}
return crc;
}
uint16_t crc16(const unsigned char *data_p, unsigned char length)
{
uint16_t x;
uint16_t crc = 0xFFFF;
while (length--)
{
x = crc >> 8 ^ *data_p++;
x ^= x >> 4;
crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x << 5)) ^ ((unsigned short)x);
}
return crc;
}
DATE getLicDate()
{
time_t ttime = time(0);
tm *local_time = localtime(&ttime);
int hoursSeconds = 3600 * local_time->tm_hour;
int minutesSeconds = 60 * local_time->tm_min;
int seconds = 1 * local_time->tm_sec;
int totalSeconds = hoursSeconds + minutesSeconds + seconds;
#ifdef EZ_LIC_DEBUG
DATE dateOnly = ttime - totalSeconds + 7200; // (pro win); // 7200 + vteřina za dvě hodiny pro srování
#else
DATE dateOnly = ttime - totalSeconds;
#endif
return dateOnly;
}
string getDate()
{
auto r = std::chrono::system_clock::now();
auto rp = std::chrono::system_clock::to_time_t(r);
std::string h(ctime(&rp)); // converting to c++ string
return h;
}
int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new()))
return -1;
/*
* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits
*/
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
{
EVP_CIPHER_CTX_free(ctx);
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))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
ciphertext_len = len;
/*
* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new()))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
/*
* Initialise the decryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits
*/
if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
{
EVP_CIPHER_CTX_free(ctx);
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))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
plaintext_len = len;
/*
* Finalise the decryption. Further plaintext bytes may be written at
* this stage.
*/
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
plaintext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
// converts character array
// to string and returns it
string convertToString(char *a, int size)
{
int i;
string s = "";
for (i = 0; i < size; i++)
{
s = s + a[i];
}
return s;
}
std::string base64_decode(const std::string &in)
{
std::string out;
std::vector<int> T(256, -1);
unsigned int i;
for (i = 0; i < 64; i++)
T[base64_url_alphabet[i]] = i;
int val = 0, valb = -8;
for (i = 0; i < in.length(); i++)
{
unsigned char c = in[i];
if (T[c] == -1)
break;
val = (val << 6) + T[c];
valb += 6;
if (valb >= 0)
{
out.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}
std::string base64_encode_ai(const std::string &input)
{
std::string encoded;
size_t input_length = input.length();
size_t i = 0;
while (i < input_length)
{
unsigned char input_chunk[3] = {0};
size_t chunk_size = 0;
// Fill the input chunk with up to 3 bytes from the input string
for (size_t j = 0; j < 3; ++j)
{
if (i < input_length)
{
input_chunk[j] = input[i++];
++chunk_size;
}
}
// Encode the input chunk into 4 Base64 characters
encoded += base64_chars[(input_chunk[0] & 0xFC) >> 2];
encoded += base64_chars[((input_chunk[0] & 0x03) << 4) |
((input_chunk[1] & 0xF0) >> 4)];
encoded += (chunk_size > 1)
? base64_chars[((input_chunk[1] & 0x0F) << 2) |
((input_chunk[2] & 0xC0) >> 6)]
: '=';
encoded += (chunk_size > 2)
? base64_chars[input_chunk[2] & 0x3F]
: '=';
}
return encoded;
}
unordered_map<string, string> getArguments(int argc, char *argv[])
{
const char splitChar = '=';
unordered_map<string, string> 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;
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];
}
}
result.insert(make_pair(argName, argValue));
}
return result;
}
string getCompletePath(string fileName)
{
#ifdef EZ_LIC_DEBUG
return fileName;
#else
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
}
void appendStringToVector(const std::string &str, std::vector<unsigned char> &charVector)
{
size_t strLength = str.length();
for (size_t i = 0; i < strLength; ++i)
{
charVector.push_back(static_cast<unsigned char>(str[i]));
}
}
uint16_t calculateCRC16(std::vector<char> &charVector)
{
const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
uint16_t crc = 0xFFFF; // Initial value
size_t length = charVector.size();
for (size_t i = 0; i < length; i++)
{
crc ^= charVector[i]; // XOR with the current data byte
for (int j = 0; j < 8; j++)
{
if (crc & 0x0001)
{
crc = (crc >> 1) ^ polynomial;
}
else
{
crc = crc >> 1;
}
}
}
return crc;
}
uint16_t calculateCRC16(std::vector<unsigned char> &charVector)
{
const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
uint16_t crc = 0xFFFF; // Initial value
size_t length = charVector.size();
for (size_t i = 0; i < length; i++)
{
crc ^= charVector[i]; // XOR with the current data byte
for (int j = 0; j < 8; j++)
{
if (crc & 0x0001)
{
crc = (crc >> 1) ^ polynomial;
}
else
{
crc = crc >> 1;
}
}
}
return crc;
}
uint16_t calculateCRC16(std::vector<unsigned char> &charVector, int removeCount)
{
const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
uint16_t crc = 0xFFFF; // Initial value
size_t length = charVector.size();
length = length - removeCount;
for (size_t i = 0; i < length; i++)
{
crc ^= charVector[i]; // XOR with the current data byte
for (int j = 0; j < 8; j++)
{
if (crc & 0x0001)
{
crc = (crc >> 1) ^ polynomial;
}
else
{
crc = crc >> 1;
}
}
}
return crc;
}
uint32_t bytesToDword(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
{
return static_cast<uint32_t>(byte1) |
(static_cast<uint32_t>(byte2) << 8) |
(static_cast<uint32_t>(byte3) << 16) |
(static_cast<uint32_t>(byte4) << 24);
}
uint32_t bytesToWord(uint8_t byte1, uint8_t byte2)
{
return static_cast<uint32_t>(byte1) | (static_cast<uint32_t>(byte2) << 8);
}
std::vector<unsigned char> joinVectors(const std::vector<unsigned char> &vector1, const std::vector<unsigned char> &vector2)
{
std::vector<unsigned char> result;
result.insert(result.end(), vector1.begin(), vector1.end());
result.insert(result.end(), vector2.begin(), vector2.end());
return result;
}
bool readFile(string fileName, vector<char> &output)
{
std::ifstream file(fileName, std::ios::in | std::ios::binary);
if (file.is_open() != 1)
{
return false;
}
char byte;
while (file.get(byte))
{
// Convert the char to unsigned char and push it into the vector
output.push_back(byte);
}
file.close();
return true;
}
#endif

29
src/common/utils.d Normal file
View File

@@ -0,0 +1,29 @@
src/common/utils.o: src/common/utils.cpp include/common/utils.h \
include/common/licConnector.h include/common/lic_config.h \
include/openssl/conf.h include/openssl/macros.h \
include/openssl/opensslconf.h include/openssl/configuration.h \
include/openssl/opensslv.h include/openssl/bio.h include/openssl/e_os2.h \
include/openssl/crypto.h include/openssl/safestack.h \
include/openssl/stack.h include/openssl/types.h \
include/openssl/cryptoerr.h include/openssl/symhacks.h \
include/openssl/cryptoerr_legacy.h include/openssl/core.h \
include/openssl/bioerr.h include/openssl/lhash.h \
include/openssl/conferr.h include/openssl/conftypes.h \
include/openssl/ssl.h include/openssl/comp.h include/openssl/comperr.h \
include/openssl/x509.h include/openssl/buffer.h \
include/openssl/buffererr.h include/openssl/evp.h \
include/openssl/core_dispatch.h include/openssl/evperr.h \
include/openssl/params.h include/openssl/bn.h include/openssl/bnerr.h \
include/openssl/objects.h include/openssl/obj_mac.h \
include/openssl/asn1.h include/openssl/asn1err.h \
include/openssl/objectserr.h include/openssl/ec.h \
include/openssl/ecerr.h include/openssl/rsa.h include/openssl/rsaerr.h \
include/openssl/dsa.h include/openssl/dh.h include/openssl/dherr.h \
include/openssl/dsaerr.h include/openssl/sha.h include/openssl/x509err.h \
include/openssl/x509_vfy.h include/openssl/pkcs7.h \
include/openssl/pkcs7err.h include/openssl/http.h include/openssl/pem.h \
include/openssl/pemerr.h include/openssl/hmac.h include/openssl/async.h \
include/openssl/asyncerr.h include/openssl/ct.h include/openssl/cterr.h \
include/openssl/sslerr.h include/openssl/sslerr_legacy.h \
include/openssl/prov_ssl.h include/openssl/ssl2.h include/openssl/ssl3.h \
include/openssl/tls1.h include/openssl/dtls1.h include/openssl/srtp.h

BIN
src/common/utils.o Normal file

Binary file not shown.

2
src/csd Normal file
View File

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

Some files were not shown because too many files have changed in this diff Show More