-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpr06_ecard.cpp
More file actions
490 lines (437 loc) · 15.3 KB
/
Copy pathpr06_ecard.cpp
File metadata and controls
490 lines (437 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/* This example demonstrates how to read and process data from ECards (including
* RFID documents).
*
* - ECard selection
* - Performing authentications before starting reading ECard data (necessary
* to access certain data files).
* - Reading all available files from the ECard.
* - Analyzing read binary data and displaying the detailed content in the
* same way as in pr04_analyze.
*
* Note, that this program performs the steps of the reading process one by
* one. As an alternate solution, refer to the ReadDoc GUI sample program.
*/
#include "Pr22.hpp"
#include <iostream>
#include <iomanip>
#include <sys/stat.h>
#ifdef WIN32
#include <conio.h>
#include <io.h>
#else
#include <sys/types.h>
#include <dirent.h>
#endif
namespace tutorial
{
using namespace Pr22;
using namespace Pr22::Processing;
class SampleFilesys
{
static bool Match(const char *s, const char *m);
static void AddFiles(std::vector<std::string> &Files, const std::string &Directory,
const std::string &Pattern);
public:
static bool IsDir(const std::string &Entry);
static bool IsFile(const std::string &Entry);
static std::vector<std::string> ListFiles(const std::string &Directory,
const std::string &Pattern);
};
//--------------------------------------------------------------------------
class MainClass : public Events::DocEventHandler
{
DocumentReaderDevice *pr;
public:
MainClass() : pr(0) { }
~MainClass() { delete pr; }
//----------------------------------------------------------------------
// Opens the first document reader device.
int Open()
{
std::wcout << L"Opening a device" << std::endl;
std::wcout << std::endl;
pr = new DocumentReaderDevice();
pr->AddEventHandler(Events::Event::Connection, this);
pr->AddEventHandler(Events::Event::DeviceUpdate, this);
try { pr->UseDevice(0); }
catch(const Exceptions::NoSuchDevice &)
{
std::wcout << L"No device found!" << std::endl;
return 1;
}
std::wcout << L"The device " << pr->DeviceName() << L" is opened." << std::endl;
std::wcout << std::endl;
return 0;
}
//----------------------------------------------------------------------
// Loads certificates from a directory.
void LoadCertificates(const std::string &dir)
{
std::string exts[] = { "*.cer", "*.crt", "*.der", "*.pem", "*.crl", "*.cvcert", "*.ldif", "*.ml" };
int cnt = 0;
for(unsigned int exti=0; exti<gx_arraycnt(exts); ++exti)
{
std::vector<std::string> list = SampleFilesys::ListFiles(dir, exts[exti]);
for(unsigned int fix=0; fix<list.size(); ++fix)
{
std::string &file = list[fix];
try
{
BinData priv;
if(exts[exti] == "*.cvcert") {
//Searching for private key
std::string pk = file.substr(0, file.find_last_of('.') + 1).append("pkcs8");
if(SampleFilesys::IsFile(pk)) priv.Load(pk);
}
pr->GlobalCertificateManager().Load(BinData().Load(file), priv);
std::cout << "Certificate " << file << " is loaded" <<
(priv.RawSize() ? " with private key." : ".") << std::endl;
++cnt;
}
catch(const Pr22::Exceptions::General &) {
std::cout << "Loading certificate " << file << " is failed!" << std::endl;
}
}
}
if(cnt == 0) std::cout << "No certificates loaded from " << dir << std::endl;
std::cout << std::endl;
}
//----------------------------------------------------------------------
// Does an authentication after collecting the necessary information.
bool Authenticate(ECard &SelectedCard, const ECardHandling::AuthProcess &CurrentAuth)
{
BinData AdditionalAuthData;
int selector = 0;
switch(CurrentAuth)
{
case ECardHandling::AuthProcess::BAC:
case ECardHandling::AuthProcess::PACE:
case ECardHandling::AuthProcess::BAP:
{
//Read MRZ (necessary for BAC, PACE and BAP)
std::wcout << L"- Getting MRZ for " << CurrentAuth.ToString() << std::endl;
Task::DocScannerTask ScanTask;
ScanTask.Add(Imaging::Light::Infra);
Page FirstPage = pr->Scanner().Scan(ScanTask, Imaging::PagePosition::First);
Task::EngineTask MrzReadingTask;
MrzReadingTask.Add(FieldSource::Mrz, FieldId::All);
Document MrzDoc = pr->Engine().Analyze(FirstPage, MrzReadingTask);
AdditionalAuthData.SetString(MrzDoc.GetField(FieldSource::Mrz, FieldId::All).GetRawStringValue());
selector = 1;
break;
}
case ECardHandling::AuthProcess::Passive:
case ECardHandling::AuthProcess::Terminal:
//Load the certificates if not done yet
break;
case ECardHandling::AuthProcess::SelectApp:
std::vector<ECardHandling::Application> apps = SelectedCard.ListApplications();
if(apps.size()>0) selector = apps[0];
break;
}
try
{
std::wcout << L"- " << CurrentAuth.ToString() << L" authentication ";
SelectedCard.Authenticate(CurrentAuth, AdditionalAuthData, selector);
std::wcout << L"succeeded" << std::endl;
return true;
}
catch(const Exceptions::General &ex)
{
std::wcout << L"failed: " << ex.what() << std::endl;
return false;
}
}
//----------------------------------------------------------------------
int Program()
{
//Devices can be manipulated only after opening.
if(Open() != 0) return 1;
//Please set the appropriate path
std::wstring certdir = pr->GetProperty(L"rwdata_dir") + L"\\certs";
LoadCertificates(std::string(certdir.begin(), certdir.end()));
std::vector<ECardReader> &CardReaders = pr->Readers();
//Connecting to the 1st card of any reader
ECard SelectedCard;
int CardCount = 0;
std::wcout << L"Detected readers and cards:" << std::endl;
size_t ix;
for(ix=0; ix<CardReaders.size(); ++ix)
{
ECardReader &reader = CardReaders[ix];
std::wcout << L"\tReader: " << reader.Info().HwType().ToString() << std::endl;
std::vector<std::wstring> cards = reader.ListCards();
if(SelectedCard.Serial().empty() && cards.size()) SelectedCard = reader.ConnectCard(0);
for(size_t iy=0; iy<cards.size(); ++iy)
{
std::wcout << L"\t\t(" << CardCount++ << L")card: " << cards[iy] << std::endl;
}
std::wcout << std::endl;
}
if(SelectedCard.Serial().empty())
{
std::wcout << L"No card selected!" << std::endl;
return 1;
}
std::wcout << L"Executing authentications:" << std::endl;
ECardHandling::AuthProcess CurrentAuth = SelectedCard.GetNextAuthentication(false);
bool PassiveAuthImplemented = false;
while(CurrentAuth != ECardHandling::AuthProcess::NoAuth)
{
if(CurrentAuth == ECardHandling::AuthProcess::Passive) PassiveAuthImplemented = true;
bool authOk = Authenticate(SelectedCard, CurrentAuth);
CurrentAuth = SelectedCard.GetNextAuthentication(!authOk);
}
std::wcout << std::endl;
std::wcout << L"Reading data:" << std::endl;
std::vector<ECardHandling::File> FilesOnSelectedCard = SelectedCard.ListFiles();
if(PassiveAuthImplemented)
{
FilesOnSelectedCard.push_back(ECardHandling::FileId::CertDS);
FilesOnSelectedCard.push_back(ECardHandling::FileId::CertCSCA);
}
for(ix=0; ix<FilesOnSelectedCard.size(); ++ix)
{
try
{
ECardHandling::File &File = FilesOnSelectedCard[ix];
std::wcout << L"File: " << File.ToString() << L".";
BinData RawFileData = SelectedCard.GetFile(File);
RawFileData.Save(File.ToString() + L".dat");
Document FileData = pr->Engine().Analyze(RawFileData);
FileData.Save(Document::FileFormat::Xml).Save(File.ToString() + L".xml");
//Executing mandatory data integrity check for Passive Authentication
if(PassiveAuthImplemented)
{
ECardHandling::File f = File;
if(f.Id >= ECardHandling::FileId::GeneralData) f = SelectedCard.ConvertFileId(f);
if(f.Id >= 1 && f.Id <= 16)
{
std::wcout << L" hash check...";
std::wcout << (SelectedCard.CheckHash(f) ? L"OK" : L"failed");
}
}
std::wcout << std::endl;
PrintDocFields(FileData);
}
catch(const Exceptions::General &ex)
{
std::wcout << L" Reading failed: " << ex.what();
}
std::wcout << std::endl;
}
std::wcout << L"Authentications:" << std::endl;
Document AuthData = SelectedCard.GetAuthResult();
AuthData.Save(Document::FileFormat::Xml).Save("AuthResult.xml");
PrintDocFields(AuthData);
std::wcout << std::endl;
try { SelectedCard.Disconnect(); }
catch(const Exceptions::General &) { }
pr->CloseDevice();
return 0;
}
//----------------------------------------------------------------------
/** Prints out all fields of a document structure to console.
*
* Values are printed in three different forms: raw, formatted and standardized.
* Status (checksum result) is printed together with fieldname and raw value.
* At the end, images of all fields are saved into png format.
*/
static void PrintDocFields(const Document &doc)
{
std::vector<FieldReference> Fields = doc.ListFields();
std::wcout << L" " << std::setw(20) << std::left << L"FieldId" << std::setw(17) << L"Status" << L"Value" << std::endl;
std::wcout << L" " << std::setw(20) << L"-------" << std::setw(17) << L"------" << L"-----" << std::endl;
std::wcout << std::endl;
size_t ix;
for(ix=0; ix<Fields.size(); ++ix)
{
try
{
Field CurrentField = doc.GetField(Fields[ix]);
std::wstring Value, FormattedValue, StandardizedValue;
std::vector<gxu8> binValue;
try { Value = CurrentField.GetRawStringValue(); }
catch(const Exceptions::EntryNotFound &) { }
catch(const Exceptions::InvalidParameter &) { binValue = CurrentField.GetBinaryValue(); }
try { FormattedValue = CurrentField.GetFormattedStringValue(); }
catch(const Exceptions::EntryNotFound &) { }
try { StandardizedValue = CurrentField.GetStandardizedStringValue(); }
catch(const Exceptions::EntryNotFound &) { }
//std::wstring Amid = GetAmid(CurrentField);
//std::wstring StdName = CurrentField.StdId();
Status Status = CurrentField.GetStatus();
std::wstring Fieldname = Fields[ix].ToString();
if(binValue.size())
{
std::wcout << L" " << std::setw(20) << Fieldname << std::setw(17) << Status.ToString() << L"Binary" << std::endl;
//// Binary data can be printed out here
//for(size_t cnt=0; cnt<binValue.size(); cnt+=16)
// std::wcout << PrintBinary(binValue, (int)cnt, 16, true) << std::endl;
}
else
{
std::wcout << L" " << std::setw(20) << Fieldname << std::setw(17) << Status.ToString() << L"[" << Value << L"]" << std::endl;
//if(Amid.length()) std::wcout << L" " << Amid << std::endl;
//if(StdName.length()) std::wcout << L" (" << StdName << L")" << std::endl;
std::wcout << L"\t" << std::setw(31) << L" - Formatted" << L"[" << FormattedValue << L"]" << std::endl;
std::wcout << L"\t" << std::setw(31) << L" - Standardized" << L"[" << StandardizedValue << L"]" << std::endl;
}
std::vector<Checking> lst = CurrentField.GetDetailedStatus();
for(size_t iy=0; iy<lst.size(); ++iy)
{
std::wcout << lst[iy].ToString() << std::endl;
}
try { CurrentField.GetImage().Save(Imaging::RawImage::FileFormat::Png).Save(Fieldname + L".png"); }
catch(const Exceptions::General &) { }
}
catch(const Exceptions::General &) { }
}
std::wcout << std::endl;
std::vector<FieldCompare> comp = doc.GetFieldCompareList();
for(ix=0; ix<comp.size(); ++ix)
{
std::wcout << L"Comparing " << comp[ix].Field1.ToString() << L" vs. "
<< comp[ix].Field2.ToString() << L" results " << comp[ix].Confidence << std::endl;
}
std::wcout << std::endl;
}
//----------------------------------------------------------------------
// Event handlers
//----------------------------------------------------------------------
void OnConnection(int devno)
{
std::wcout << L"Connection event. Device number: " << devno << std::endl;
}
//----------------------------------------------------------------------
void OnDeviceUpdate(int part)
{
std::wcout << L"Update event." << std::endl;
switch(part)
{
case 1:
std::wcout << L" Reading calibration file from device." << std::endl;
break;
case 2:
std::wcout << L" Scanner firmware update." << std::endl;
break;
case 4:
std::wcout << L" RFID reader firmware update." << std::endl;
break;
case 5:
std::wcout << L" License update." << std::endl;
break;
}
}
//----------------------------------------------------------------------
};
//--------------------------------------------------------------------------
bool SampleFilesys::IsDir(const std::string &Entry)
{
struct stat s;
if(stat(Entry.c_str(), &s)) return false;
if(!(s.st_mode & S_IFDIR)) return false;
return true;
}
//--------------------------------------------------------------------------
bool SampleFilesys::IsFile(const std::string &Entry)
{
struct stat s;
if(stat(Entry.c_str(), &s)) return false;
if(!(s.st_mode & S_IFREG)) return false;
return true;
}
//--------------------------------------------------------------------------
bool SampleFilesys::Match(const char *s, const char *m)
{
while(*s && *m) {
if(*s == *m || *m == '?') {
// Continue on character match or on ? wildcard
s++; m++;
}
else if(*m == '*') {
// Check for * wildcard, recursively for each possible matching
while(*m=='*') m++;
if(!*m) return true;
while(*s && *m != *s) s++;
if(!*s) return false;
if(Match(s, m)) return true;
s++; m--;
}
else {
return false;
}
}
while(*m=='*') m++;
return (!*s && !*m);
}
//--------------------------------------------------------------------------
std::vector<std::string> SampleFilesys::ListFiles(const std::string &Directory,
const std::string &Pattern)
{
std::vector<std::string> Files;
if(IsDir(Directory)) AddFiles(Files, Directory, Pattern);
return Files;
}
//--------------------------------------------------------------------------
#ifdef WIN32
void SampleFilesys::AddFiles(std::vector<std::string> &Files,
const std::string &Directory, const std::string &Pattern)
{
#if _MSC_VER >= 1400
intptr_t d;
#else
int d;
#endif
struct _finddata_t de;
std::string dn = Directory + "\\*.*";
d = _findfirst((char*)dn.c_str(), &de);
do {
if(!strcmp(de.name, ".") || !strcmp(de.name, "..")) continue;
dn = Directory + "\\" + de.name;
if(IsDir(dn)) AddFiles(Files, dn, Pattern);
else if(Match(de.name, Pattern.c_str())) Files.push_back(dn);
} while (_findnext(d, &de) != -1);
_findclose(d);
}
#endif
#ifdef LINUX
void SampleFilesys::AddFiles(std::vector<std::string> &Files,
const std::string &Directory, const std::string &Pattern)
{
DIR *d = opendir(Directory.c_str());
if(!d) return;
struct dirent *de;
while((de = readdir(d))) {
if(!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
std::string dn = Directory + "/" + de->d_name;
if(IsDir(dn)) AddFiles(Files, dn, Pattern);
else if(Match(de->d_name, Pattern.c_str())) Files.push_back(dn);
}
closedir(d);
}
#endif
//--------------------------------------------------------------------------
}
int main()
{
#if defined(WIN32) && !defined(__BORLANDC__)
setlocale(LC_CTYPE, ".OCP");
#else
setlocale(LC_CTYPE, "");
#endif
try
{
tutorial::MainClass prog;
prog.Program();
}
catch(const Pr22::Exceptions::General &ex)
{
std::wcerr << ex.what() << std::endl;
}
#ifdef WIN32
std::wcout << L"Press any key to exit!" << std::endl;
_getch();
#endif
return 0;
}