-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
654 lines (600 loc) · 20.3 KB
/
lib.js
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
const pkcs11js = require("pkcs11js");
const { createVerify, randomBytes, createHash, createCipheriv, createDecipheriv } = require("crypto");
class CardReader {
constructor(moduleFileName) {
this.pkcs11 = new pkcs11js.PKCS11();
this.pkcs11.load(moduleFileName || "beidpkcs11.dll");
this.Init();
this.objectNames = [
"ATR",
"CARD_DATA",
"carddata_serialnumber",
"carddata_comp_code",
"carddata_os_number",
"carddata_os_version",
"carddata_soft_mask_number",
"carddata_soft_mask_version",
"carddata_appl_version",
"carddata_glob_os_version",
"carddata_appl_int_version",
"carddata_pkcs1_support",
"carddata_key_exchange_version",
"carddata_appl_lifecycle",
"DATA_FILE",
"card_number",
"chip_number",
"validity_begin_date",
"validity_end_date",
"issuing_municipality",
"national_number",
"surname",
"firstnames",
"first_letter_of_third_given_name",
"nationality",
"location_of_birth",
"date_of_birth",
"gender",
"nobility",
"document_type",
"special_status",
"photo_hash",
"ADDRESS_FILE",
"address_street_and_number",
"address_zip",
"address_municipality",
"PHOTO_FILE",
"CERT_RN_FILE",
"SIGN_DATA_FILE",
"SIGN_ADDRESS_FILE",
];
Object.freeze(this.objectNames);
}
/**
* Initialize the module.
*/
Init() {
this.pkcs11.C_Initialize();
}
/**\
* Call this function at the end of your code.
* This will end the conversation with the cardreader and you will need to initialize again.
*/
Finalize() {
this.pkcs11.C_Finalize();
}
/**
* Gets the a List of solts(cardreader) found
* @param {Boolean} searchCards search cards(true) or only cardreades(false) default is false
* @returns List of slots
*/
GetSlotList(searchCards = false) {
try {
return this.pkcs11.C_GetSlotList(searchCards);
} catch (e) {
console.log(e)
}
}
/**
* Get the first available slot that has a card in it.
* @returns A slot
*/
GetAvailableSlot() {
const slots = this.GetSlotList(true);
if (slots.length == 0)
return null
return slots[0];
}
/**
* Check if a reader has a card in it
* @returns boolean
*/
HasCard() {
return this.GetAvailableSlot() != null;
}
/**
* Gets the description of the first slot (cardreader) found
* @param slot a slot
* @returns Description of the first slot found
*/
GetSlotDescription(slot) {
return this.pkcs11.C_GetSlotInfo(slot);
}
/**
* Tries to create a Session, returns NULL in case of failure
* @param {Buffer} slot a slot
* @returns A session or null
*/
CreateSession(slot) {
try {
return this.pkcs11.C_OpenSession(slot, pkcs11js.CKF_RW_SESSION | pkcs11js.CKF_SERIAL_SESSION);
} catch {
return null;
}
}
/**
* Gets label of token found in the first non-empty slot (cardreader)
* @param {Buffer} slot A slot
* @returns token info of a slot
*/
GetTokenInfo(slot) {
let tokenInfoLabel;
try {
tokenInfoLabel = this.pkcs11.C_GetTokenInfo(slot);
} catch (err) {
console.log(err)
}
return tokenInfoLabel;
}
/**
* Get special status of the owner of the card
* @returns special status string
*/
GetSpecialStatus() {
return this.GetData("special_status");
}
/**
* Get firstname of the owner of the card
* @returns firstname string
*/
GetFirstName() {
return this.GetData("firstnames");
}
/**
* Get surname of the owner of the card
* @returns surname string
*/
GetSurname() {
return this.GetData("surname");
}
/**
* Get birth date of the owner of the card
* @returns birth date string
*/
GetDateOfBirth() {
return this.GetData("date_of_birth");
}
/**
* Get gender of the owner of the card
* @returns gender string
*/
GetGender() {
return this.GetData("gender");
}
/**
* Get nationality of the owner of the card
* @returns nationality string
*/
GetNationality() {
return this.GetData("nationality");
}
/**
* Get national number of the owner of the card
* @returns national number string
*/
GetNationalNumber() {
return this.GetData("national_number");
}
/**
* Get location of birth of the owner of the card
* @returns location of birth string
*/
GetLocationOfBirth() {
return this.GetData("location_of_birth");
}
/**
* Get street and number of the owner of the card
* @returns street and number string
*/
GetStreetAndNumber() {
return this.GetData("address_street_and_number");
}
/**
* Get zip/postal code of the owner of the card
* @returns zip/postal code string
*/
GetAddressZip() {
return this.GetData("address_zip");
}
/**
* Get adress municipality of the owner of the card
* @returns adress municipality string
*/
GetAddressMunicipality() {
return this.GetData("address_municipality");
}
/**
* Get nobility of the owner of the card
* @returns nobility string
*/
GetNobility() {
return this.GetData("nobility");
}
/**
* Get fullname(first + surname) of the owner of the card
* @returns fullname string
*/
GetFullName() {
return `${this.GetFirstName()} ${this.GetSurname()}`;
}
/**
* Generic function to get string data objects from label
* @param {String} label Value of label attribute of the object
* @returns string value of the object you requested via the label param
*/
GetData(label) {
let value = "";
try {
// Get the first slot (cardreader) with a token
const slotlist = this.pkcs11.C_GetSlotList(true);
if (slotlist.length > 0) {
const slot = slotlist[0];
const session = this.CreateSession(slot);
if (session != null) {
// Search for objects
// First, define a search template
const template = [
{
type: pkcs11js.CKA_CLASS,
value: pkcs11js.CKO_DATA,
},
{
type: pkcs11js.CKA_LABEL,
value: label,
}
];
this.pkcs11.C_FindObjectsInit(session, template);
const foundObjects = this.pkcs11.C_FindObjects(session, 50);
let counter = foundObjects.length;
while (counter > 0) {
const data = foundObjects[counter - 1];
const attrs = this.pkcs11.C_GetAttributeValue(session, data, [
{ type: pkcs11js.CKA_VALUE }
]);
if (attrs[0]) {
value = attrs[0].value.toString();
break;
}
counter--;
}
this.pkcs11.C_FindObjectsFinal(session);
}
} else {
console.log("No card found");
}
} catch (err) {
console.log(err)
}
return value;
}
/**
* ( Development use only ) Gets all labels for objects that are available in the slot.
* Most common are found in the objectNames array.
*/
_getAllObjectsFromSlot() {
try {
const slotlist = this.pkcs11.C_GetSlotList(true);
if (slotlist.length > 0) {
const slot = slotlist[0];
const session = this.CreateSession(slot);
if (session != null) {
this.pkcs11.C_FindObjectsInit(session, [{ type: pkcs11js.CKA_CLASS, value: pkcs11js.CKO_DATA }]);
let hObject = this.pkcs11.C_FindObjects(session);
while (hObject) {
const attrs = this.pkcs11.C_GetAttributeValue(session, hObject, [
{ type: pkcs11js.CKA_CLASS },
{ type: pkcs11js.CKA_TOKEN },
{ type: pkcs11js.CKA_LABEL }
]);
// Output info for objects from token only
if (attrs[1].value[0]) {
console.log(`${attrs[2].value.toString()}, 0x${new String(hObject).charCodeAt(0).toString(16)}`);
}
hObject = this.pkcs11.C_FindObjects(session);
}
this.pkcs11.C_FindObjectsFinal(session);
}
} else {
console.log("No card detected!")
}
} catch (err) {
console.log(err)
}
}
/**
* Return ID file contents
* @returns Buffer of ID file contents
*/
GetIdFile() {
return this.GetFile("DATA_FILE");
}
/**
* Return Address file contents
* @returns Buffer of Address file contents
*/
GetAddressFile() {
return this.GetFile("ADDRESS_FILE");
}
/**
* Return Photo file contents
* @returns Buffer of Photo file contents
*/
GetPhotoFile() {
return this.GetFile("PHOTO_FILE");
}
/**
* Return signature Data file contents
* @returns Buffer of signature Data file contents
*/
GetIdSignatureFile() {
return this.GetFile("SIGN_DATA_FILE");
}
/**
* Return signature Address file contents
* @returns Buffer of signature Address file contents
*/
GetAddressSignatureFile() {
return this.GetFile("SIGN_ADDRESS_FILE");
}
/**
* Return RRN Certificate. This certificate is used to validate the file signatures
* @returns Buffer of RRN Certificate file contents
*/
GetCertificateRNFile() {
return this.GetFile("CERT_RN_FILE");
}
/**
* Return raw byte data from objects
* @param {String} Filename Label value of the object
* @returns Buffer of the content of the file
*/
GetFile(Filename) {
let value = null;
try {
// Get the first slot (cardreader) with a token
const slotlist = this.GetSlotList(true);
if (slotlist.length > 0) {
const slot = slotlist[0];
const session = this.CreateSession(slot);
// Search for objects
// First, define a search template
const template = [
{
type: pkcs11js.CKA_CLASS,
value: pkcs11js.CKO_DATA,
},
{
type: pkcs11js.CKA_LABEL,
value: Filename,
}
];
this.pkcs11.C_FindObjectsInit(session, template);
const foundObjects = this.pkcs11.C_FindObjects(session, 1);
if (foundObjects.length != 0) {
const file = foundObjects[0];
const attrs = this.pkcs11.C_GetAttributeValue(session, file, [
{ type: pkcs11js.CKA_VALUE }
]);
if (attrs.length > 0)
value = attrs[0].value;
}
this.pkcs11.C_FindObjectsFinal(session);
} else {
console.log("No card found");
}
} catch (err) {
console.log(err);
}
return value;
}
/**
* Return the "authentication" leaf certificate file
* @returns Buffer of the "authentication" leaf certificate file
*/
GetCertificateAuthenticationFile() {
return this.GetCertificateFile("Authentication");
}
/**
* Return the "signature" leaf certificate file
* @returns Buffer of the "signature" leaf certificate file
*/
GetCertificateSignatureFile() {
return this.GetCertificateFile("Signature");
}
/**
* Return the Intermediate CA certificate file
* @returns Buffer of the Intermediate CA certificate file
*/
GetCertificateCAFile() {
return this.GetCertificateFile("CA");
}
/**
* Return the root certificate file
* @returns Buffer of the root certificate file
*/
GetCertificateRootFile() {
return this.GetCertificateFile("Root");
}
/**
* Return raw byte data from objects of object class Certificate
* @param {String} Certificatename Label value of the certificate object
* @returns byte array with certificate file
*/
GetCertificateFile(Certificatename) {
let value = null;
try {
// Get the first slot (cardreader) with a token
const slotlist = this.GetSlotList(true);
if (slotlist.length > 0) {
const slot = slotlist[0];
const session = this.CreateSession(slot);
// Search for objects
// First, define a search template
const template = [
{
type: pkcs11js.CKA_CLASS,
value: pkcs11js.CKO_CERTIFICATE,
},
{
type: pkcs11js.CKA_LABEL,
value: Certificatename,
}
];
this.pkcs11.C_FindObjectsInit(session, template);
const foundObjects = this.pkcs11.C_FindObjects(session, 1);
if (foundObjects.length != 0) {
const cert = foundObjects[0];
const attrs = this.pkcs11.C_GetAttributeValue(session, cert, [
{ type: pkcs11js.CKA_VALUE },
]);
if (attrs) {
value = attrs[0].value;
}
}
this.pkcs11.C_FindObjectsFinal(session);
} else {
console.log("No card found");
}
} catch (err) {
console.log(err);
}
return value;
}
/**
* Returns a list of PKCS11 labels of the certificate on the card
* @returns List of labels of certificate objects
*/
GetCertificateLabels() {
const labels = [];
try {
// Get the first slot (cardreader) with a token
const slotlist = this.GetSlotList(true);
if (slotlist.length > 0) {
const slot = slotlist[0];
const session = this.CreateSession(slot);
// Search for objects
// First, define a search template
// "The object class of the objects should be "certificate""
const template = [
{
type: pkcs11js.CKA_CLASS,
value: pkcs11js.CKO_CERTIFICATE,
},
];
this.pkcs11.C_FindObjectsInit(session, template);
const certificates = this.pkcs11.C_FindObjects(session, 100);
for (const certificate of certificates) {
const attrs = this.pkcs11.C_GetAttributeValue(session, certificate, [
{ type: pkcs11js.CKA_LABEL }
]);
labels.push(attrs[0].value.toString());
}
this.pkcs11.C_FindObjectsFinal(session);
} else {
console.log("No card found");
}
} catch (err) {
console.log(err);
}
return labels;
}
/**
* Sign data with a named private key
* @param {Buffer} data Data to be signed
* @param {String} privateKeyLabel Label for private key. Can be "Signature" or "Authentication"
* @returns Signed data
*/
SignWithCard(data, privateKeyLabel) {
let encryptedData = null;
try {
const slotlist = this.GetSlotList(true);
if (slotlist.length > 0) {
const slot = slotlist[0];
const session = this.CreateSession(slot);
const template = [
{
type: pkcs11js.CKA_CLASS,
value: pkcs11js.CKO_PRIVATE_KEY,
},
{
type: pkcs11js.CKA_LABEL,
value: privateKeyLabel,
},
];
this.pkcs11.C_FindObjectsInit(session, template);
const privatekeys = this.pkcs11.C_FindObjects(session, 1);
this.pkcs11.C_FindObjectsFinal(session);
if (privatekeys.length >= 1) {
this.pkcs11.C_SignInit(session, { mechanism: pkcs11js.CKM_SHA256_RSA_PKCS }, privatekeys[0]);
this.pkcs11.C_SignUpdate(session, data);
encryptedData = this.pkcs11.C_SignFinal(session, Buffer.alloc(256));
}
} else {
console.log("No card detected!")
}
} catch (err) {
console.log(err)
}
return encryptedData;
}
/**
* Verify a signature with a given certificate. It is assumed that the signature is made from a SHA1 hash of the data.
* @param {Buffer} data Signed data
* @param {Buffer} signature Signature to be verified
* @param {Buffer} publicCertificate Certificate containing the public key used to verify the code
* @returns True if the verification succeeds
*/
Verify(data, signature, publicCertificate) {
try {
const verify = createVerify("RSA-SHA256");
verify.update(data);
verify.end();
return verify.verify(this._derToPem(publicCertificate), signature);
}
catch (err) {
console.log(err);
return false;
}
}
/**
* Encrypted data wite your card
* @param {Buffer} data Data that needs to be encrypted
* @returns Encrypted data
*/
EncrypteData(data) {
const keyRandom = randomBytes(128);
const key = this.SignWithCard(keyRandom, "Authentication");
const hash = createHash('sha256').update(key).digest("base64");
const iv = randomBytes(16);
const cipher = createCipheriv("aes-256-gcm", Buffer.from(hash, "base64"), iv);
const cipherString = Buffer.concat([cipher.update(data), cipher.final()]);
const tag = cipher.getAuthTag().toString("base64");
return keyRandom.toString("base64").concat(".").concat(iv.toString("base64")).concat(".").concat(tag).concat(".").concat(cipherString.toString("base64"));
}
/**
* Decrypt data wite your card
* @param {string} cipherData Data that has been encrypted
* @returns Decrypted data
*/
DecrypteData(cipherData) {
const [keyRandom, iv, tag, data] = cipherData.split(".");
console.log(keyRandom);
console.log(data)
console.log(iv);
console.log(tag);
const key = this.SignWithCard(Buffer.from(keyRandom, "base64"), "Authentication");
const hash = createHash('sha256').update(key).digest("base64");
const decipher = createDecipheriv("aes-256-gcm", Buffer.from(hash, "base64"), Buffer.from(iv, "base64"));
decipher.setAuthTag(Buffer.from(tag, "base64"));
return decipher.update(data, "base64") + decipher.final();
}
/**
* Convert a der format file into a pem format file
* @param {Buffer} derBuffer
*/
_derToPem(derBuffer) {
const prefix = '-----BEGIN CERTIFICATE-----\n';
const postfix = '-----END CERTIFICATE-----';
return prefix + derBuffer.toString('base64').match(/.{0,64}/g).join('\n') + postfix;
}
}
module.exports = CardReader;